FSA基本的にツリーである有限状態オートマトン ( ) を作成しています。単語の各文字がノード ( State) を構成します。文字列は を通るパスを構成し、FSAパスは重複する可能性があります。ただし、ノードのnext_states、または子に問題があるようです。
入力ファイル はvocab.small次のようになり、\n各行の末尾に があります。
A
A A A
A A B E R G
A A C H E N
現在、FSAツリーに非常に似たものを構築していますが、 State start_stateandを作成しState end_stateてそれらをリンクしています。
class State (object):
__slots__ = "chars","next_states"
def __init__(self,chars,next_states=[]):
self.chars = chars
self.next_states = next_states
class FSA (object):
__slots__ = "vocab","start_state","end_state"
def __init__(self,vocab):
self.vocab = vocab
self.start_state = State("0")
self.end_state = State("1")
self.end_state.next_states.append(self.start_state)
self.start_state.next_states.append(self.end_state)
の他のメソッドは次のFSAとおりです。
def create_fsa(self):
vocab_file = open(self.vocab, 'r')
for word in vocab_file:
self.add_word(word)
vocab_file.close()
def add_word(self,word,current_state=None):
next_char = word[0:2]
if current_state == None:
current_state = self.start_state
## next_char found in current_state.next_states
if next((x for x in current_state.next_states if x.chars == next_char), None):
if len(word) > 3:
print "next_char found"
current_state = next((x for x in current_state.next_states if x.chars == next_char), None)
self.add_word(word[2:],current_state)
else:
print "next_char found + add end"
current_state = next((x for x in current_state.next_states if x.chars == next_char), None)
current_state.next_states.append(self.end_state)
## current_state.children[current_state.children.index(next_char)].append(self.end_state)
## next_char NOT found in current_state.next_states
else:
current_state.next_states.append(State(next_char))
current_state = next((x for x in current_state.next_states if x.chars == next_char), None)
if len(word) > 3:
print "next_char added"
self.add_word(word[2:],current_state)
else:
print "next_char added + end"
current_state.next_states.append(self.end_state)
print
current_state.next_states[]新しい ごとに新しく作成されるのではなく、オブジェクトが発生し続けるため、問題は にあるようStateです。新しいオブジェクトcurrent_state.next_states.append(State(next_char))を作成する方法に問題がありますか?State
助けてくれてありがとう。