class NGramIterator(object): """Unicode文字列のN-Gramを返すIterator""" def __init__(self, uni, n): super(NGramIterator, self).__init__() self.uni = uni self.n = n self.loop = -1 def next(self): if self.loop + self.n >= len(self.uni): raise StopIteration self.loop += 1 return self.uni[self.loop:self.loop+self.n] # Python 3.X 用 __next__ = next def __iter__(self): return self
動かすとこんな感じ。
>>> [n_gram for n_gram in NGramIterator(u'python',3)] [u'pyt', u'yth', u'tho', u'hon'] >>> for n_gram in NGramIterator(u'パイソン愛を語る',4): ... print n_gram ... パイソン イソン愛 ソン愛を ン愛を語 愛を語る
同様にジェネレータも作ってみた。
def n_gram_generator(uni,n): u"""Unicode文字列のN-Gramを返すGenerator """ loop = 0 while loop + n <= len(uni): yield uni[loop:loop+n] loop += 1なんともシンプル。 こちらも動かすとこんな感じ。
>>> [n_gram for n_gram in n_gram_generator('n-grams',2)] ['n-', '-g', 'gr', 'ra', 'am', 'ms'] >>> for n_gram in n_gram_generator(u'自然言語処理にハマる',5): ... print n_gram ... 自然言語処 然言語処理 言語処理に 語処理にハ 処理にハマ 理にハマる
ジェネレータって全然使ったことなかったけど、かなり便利だね。
0 件のコメント:
コメントを投稿