XとYを含むn-gramの文章を取るプログラム
最近Pythonをよく使ってます。
そこで、ある2つの単語(XとY)を含む、5文字以内の部分文字列を取る必要があったので、プログラムを書いてみました。
#! coding: utf-8 str = 'ggggg bbbb cccc X is large Y hoge aaa xxxx yyyy X is small Y hogehoge aaaa hoge' windowSize = 5 tokens = str.split(' ') for i in range(len(tokens)-1): XisIncludedFlag = False YisIncludedFlag = False for j in range(windowSize): if tokens[i+j] == 'X' : XisIncludedFlag = True if tokens[i+j] == 'Y' : YisIncludedFlag = True if i+j == len(tokens)-1 : break if XisIncludedFlag and YisIncludedFlag : for j in range(windowSize): print tokens[i+j] if i + j == len(tokens)-1 : break print ''
例えば、strとして、
str = 'ggggg bbbb cccc X is large Y hoge aaa xxxx yyyy X is small Y hogehoge aaaa hoge'
という文章を使った時、(print tokens[i+j]によって)出力されるのは、
cccc X is large Y X is large Y hoge yyyy X is small Y X is small Y hogehoge
です。
ただ、場当たり的に書いたので、すごく遅いプログラムになってると思います。
このプログラムでは、対象文字列がN文字あったとき、今回はwindowSizeが5なので、大体 N * 5ほど実行回数が必要になります。
たぶん探せばもっといいアルゴリズムがたくさんあるはず…。