Python: 文字列処理もいい加減覚えたい!?遅いよねぇ?(随時更新)
文字列の色々をどんどん書いていくエントリにしようと思います。新しいこと覚えたら書き足していく方向で。
Findなど。あとインデックスの注意。
あるかどうかの確認だけなら、 XXX in YYYYで、XXXがYYYYの中にあるかどうか真偽値を返してくれます。
findは最初の文字を見つけてくれます。一番最後を見つけるのはrfind.
これはpython全体だけど、特に文字列切ったりするときにはインデックスの範囲に注意。Pythonのリストだと、最後の数字は範囲外。
>>> okotoba = "All your Bayes are belong to us!"
>>> "Bayes" in okotoba
True
>>> Bayes_index = okotoba.find("Bayes")
>>> print Bayes_index # 先頭から10文字目にBがいる
9
>>> o_index = okotoba.rfind("o") # "to" の "o"を見つけた
>>> print okotoba[0:o_index-1]
All your Bayes are belong
>>> print okotoba[0:o_index]
All your Bayes are belong t
>>> print okotoba[1:o_index]
ll your Bayes are belong t>>> no_index = okotoba.find("Vapnik") # ない時は-1を返します
>>> print no_index
-1
Perlでいうところのchomp(). 文末の空白・改行文字を除外。
rstrip()をつかいましょう。
切ったりつなげたり
>>> str1 = "homuhomu"
>>> str2 = "kawaii"
>>> str3 = str1 + str2 # わかりやすくていいね!
>>> print str3
homuhomukawaii
>>> split_list = str3.split("o") # 指定の文字で切る
>>> print split_list
['h', 'muh', 'mukawaii']
>>> str4 = "Scott, beam me up!!"
>>> split_list = str4.split() # 指定しないと空白で切る?
>>> print split_list
['Scott,', 'beam', 'me', 'up!!']
空白区切りspliの挙動については
Python: splitによる区切りの挙動 - Bag of ML Words
に注意です。
joinによる連結
+よりはjoin()を使ったほうがいいぽいです。
>>> str1 = split_list.join() # joinは文字列型の関数みたいです
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute 'join'
>>> str1 = "".join(split_list) #最初のやつは、無名コンストラクタ的なアレですかね
>>> print str1
Scott,beammeup!!
>>> str2 = " ".join(split_list) # ただの無名コンストラクタじゃなかった!結合文字だった!頭いい実装だ
>>> print str2
Scott, beam me up!!
数値にしたり
単体の文字列ならばfloat(), int()でOK。
>>> str1 = "1.0"
>>> a = float(str1)>>> print a # flaotですね
1.0
>>> b = int(str1) # integerへのキャストはしてくれないみたいです・・・
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.0'
>>> str2 = "2">>> c = float(str2)
>>> d = int(str2)
>> print c # float
2.0
>>> print d # integer
2
一方、文字列のリストを数値リストの変えるのは知らなかったのですが、
mapを使うようですね。
>>> num_str_list = ["1.0", "-0.3", "-4.5"]
>>> num_list = map(float, num_str_list)
>>> print num_list
[1.0, -0.3, -4.5]
このmap、第一引数の関数を第二引数のリスト要素の順番に適用するってことらしい。明示的にfor文呼ぶよりも早いのかなぁ。
置換
文字列の置換については
Pythonでの文字列置換をマスターする - orangain flavor
を参考にさせてもらっているのですが、それは自分的に面倒なので、ここでまとめておきます。というかほぼ単純にコピーしてるだけですね。
文字列クラスのメソッドによる置換
>>> okotoba = "All your Bayes are belong to us!!"
>>> str_replace = okotoba.replace("Bayes", "Logic")
>>> print str_replace
All your Logic are belong to us!!
replaceは第三引数を取れるようです。例えばreplace("hoge, "homu", 3)だと文字列の最初の3つの"hoge"が"homu"に変わります。
そして、python 2系列とpython 3系列ってのがあるんですか。そしていろいろ変わっちゃうんですか。困りましたねぇ・・・。
とりあえずここでは2系列のお話です。3系列に乗り換えたらまた書き直します。
正規表現クラスのメソッドによる置換
もっと強力なことができるはずですね。
>>> import re
>>> print okotoba
All your Bayes are belong to us!!
>>> regular_sub = re.sub(r"[a-n]", "X", okotoba)
>>> print regular_sub
AXX your BXyXs XrX XXXoXX to us!! #伏せ字