Python基本1

  1. 組み込み型のまとめ
  • コレクション型:シーケンス型(文字列、リスト、タプル)、マップ型:辞書
  • 変更可能/不可能:リスト、辞書は変更可能。文字列、タプルは変更不可能
  1. 文字列検索と比較
  • find()メソッドでは、文字列が見つかった場合は位置を示す数値が、見つからなかった場合には-1が返ってくる。

■基本コード集

①検索

s = "this is ASCII string"

>>> if s.find("ASCII") != -1:
...     print "Ture"

 

②文字の分割、演算、再結合

def add_tax(astring):

items = astring.split()#文字列をスペースで分割

price = int(items[1])*1.05#2番目を数値に変換して1.05倍

items[1] = str(int(price))#再び文字列に変換

return " ".join(items)#スペースで連結し文字列を返す

 

add_tax("Goods 1000 2006/05/27")

 

③文字列を","で分割

"abc, def, ghi".split(",")

 

④文字列中に変数の埋め込み

#例その1

 

template = u"%sの%d月の平均気温:約%d度"

print template %  (u"東京", 6, 24)

 

#%sにある位置には文字列を埋め込む。埋め込むオブジェクトは文字列だけでなく

数値などを指定しても構わない。「%d」や「%f」のように数値型を要求する部分に

文字列を置換することは不可。整数と浮動小数点数のように、精度の異なる数値は

コードに従って変換して埋め込む。

 

#例その2

 

linkattrs = {"href":"http://host.to/path/",

"title":"My Blog"}

 

#フォーマット文字列の定義

 

formatstr = """<a href="%(href)s" title="%(title)s">

%(title)s

</a>"""

 

atag = formatstr % linkattrs

print atag

 

⑤文字列を小文字に変換してソート

def cmp_lower(a,b):

return cmp(a.lower(),b.lower())

 

#a.lower():引数を小文字に変換し、コピーを返す

#cmpは、a.lower < b.lowerのときは負の値、a.lower = b.lowerのときは0、a.lower > b.lowerのときは正の値を返す

 

a = ["abc", "def", "BCD", "EFG"]

a.sort()

a.sort(cmp_lower)

#比較用の関数を指定してソート

 

⑥ファイルを読み込み、言葉をカウント

#ファイルを読み込む

f = open("wordcount_test.py")

wordcount = {}

 

#ファイルを一行ずつ読み込む

for line in f:

 

#各行の改行を削除し、スペースで区切りリストを作成後、単語毎に処理を行う

  for word in line.rstrip().split(" "):

 

#wordcount中に"word"が存在しなければ、その"word"のカウントは0、もし存在すれば1増加

    if not word in wordcount:

      wordcount[word] = 0

    wordcount[word] += 1

 

##has_keyを用いた方法

f = open("wordcount_test.py")

wordcount = {}

for line in f:

  for word in line.rstrip().split(" "):

    if wordcount.has_key(word):

      wordcount[word] += + 1

    else:

wordcount[word] = 1