fsa3 - #!/usr/bin/env python " FSA module This module...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
#!/usr/bin/env python """ FSA module This module implements simple deterministic, non-deterministic, and weighted finite state automata. It follows the description in Chapters 2 and 6 of Jurafsky and Martin (2008). @author: Rob Malouf @organization: Dept. of Linguistics, San Diego State University @contact: rmalouf@mail.sdsu.edu @version: 3 @since: 10-April-2008 """ from copy import deepcopy class FSA(object): """ General finite-state automaton class An FSA consists of: - an alphabet (C{self.alphabet}) - a state-transition table (C{self.transition_table}) - an initial state (C{self.initial}) - a set of final states (C{self.final}) """ def __init__(self,T,finals,initial=0): """ Create a new FSA object @param T: the transition function @type T: a C{list} of C{dict}s @param finals: final states @type finals: C{list} @param initial: initial state (by default, 0) @type initial: C{int} @raise ValueError: the FSA is mis-specified somehow """ # transition function self.transition_table = T for state in self.transition_table: for symbol in state: # the value of the transition function should be a list of states if not hasattr(state[symbol],'__getitem__'): state[symbol] = [ state[symbol] ] for newState in state[symbol]: try: self.transition_table[newState] except: raise ValueError,'%s not a valid state'%newState # initial state
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
self.initial = initial try: self.transition_table[self.initial] except: raise ValueError,'%s not a valid initial state'%initial # final states try: self.finals = set(finals) for final in self.finals: self.transition_table[final] except: raise ValueError,'%s not valid final states'%finals # alphabet self.alphabet = set() for state in self.transition_table: self.alphabet.update(state.keys()) def __repr__(self): """Produce a string representation of an FSA (e.g., for printing).""" result = '{ %s\n' % (self.__class__.__name__) result += ' Alphabet : %s\n'%self.alphabet for index in xrange(len(self.transition_table)): result += ' %s:' % index if index == self.initial: result += ' initial' if index in self.finals: result += ' final' result += '\n' for key in self.transition_table[index]:
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

Page1 / 7

fsa3 - #!/usr/bin/env python " FSA module This module...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online