よく前処理に使う単語のID化を例にとって、collectionsの話
単語のID化
Is this a pen ? This is a pen .
と文字列(文)があったとすると、0 1 2 3 4 1 0 2 3 5
みたいにそれぞれの単語ごとにIDを振っていきます。
今回は大文字小文字の区別をしていません。
0
=is
, 1
=this
...とこんな感じの対応になります。
プログラムにおこすと下記のような感じになります。
サンプルコード(python3)
#usr/bin/python
#python3(3.5)
import collections
word2id = collections.defaultdict(lambda: len(word2id) )
sentence = "Is this a pen ? This is a pen ."
def convert_word(sentence):
return [word2id[word.lower()] for word in sentence.split()]
print("sentence :", sentence)
print("id_sentence :", *convert_word(sentence) )
print("dict :", dict(word2id) )
出力
sentence : Is this a pen ? This is a pen .
id_sentence : 0 1 2 3 4 1 0 2 3 5
dict : {'.': 5, '?': 4, 'is': 0, 'this': 1, 'pen': 3, 'a': 2}
今回は、.lower()
をつかって全て小文字にしてから辞書に登録しています。
辞書はcollections
モジュールの中にあるdefaultdict
を使用しています。
defaultdict
は、key
を入れた時、そのkey
が存在しなかった場合に自分で決めたものを入れといてくれるものです。
今回は、lambda: len(word2id)
とすることで、新しく入ってきたkey
に対して新しい番号を振ることができます。
他の使い方としては、collections.defaultdict(list)
とすると未知のkeyが入ってきた場合に自動でlist()
を作っといてくれます。
collections
にはCounter, OrderedDict, deque, namedtupleが入っており、どれも便利なものです。
コードはpython3用なので、python2でやる場合は最後から2行目のところを*convert_word(sentence)
から' '.join(convert_word(sentence)
にすると動きます。
python3ではprintは関数なので、*
をつかって引数として渡せますが、pythonn2ではこれでは渡せないようです。