Below is the code:
# import the fst module
from nltk.draw import *
from nltk.nltk_contrib.fst.fst import *
# import the string module
import string
# Define a list of all vowels for convenience
vowels = ['a', 'e', 'i', 'o', 'u']
special = ['?', '!', '#', '$', '&']
# Instantiate an FST object with some name
f = FST('devowelizer2')
# All we need is a single state ...
f.add_state('1')
f.add_state('2')
f.add_state('3')
# and this same state is the initial and the final state
f.initial_state = '1'
f.set_final('1')
f.set_final('2')
f.set_final('3')
# Now, we need to add an arc for each letter; if the letter is a vowel
# then transition outputs nothing but otherwise it outputs the same
# letter that it consumed.
for letter in string.ascii_lowercase:
if letter in vowels:
f.add_arc('1', '3', (letter), ('V'))
f.add_arc('2', '3', (letter), ('V'))
f.add_arc('3', '3', (letter), ('V'))
elif letter in special:
f.add_arc('1', '1', (letter), ('I'))
f.add_arc('2', '1', (letter), ('I'))
f.add_arc('3', '1', (letter), ('I'))
else:
f.add_arc('1', '2', (letter), ('C'))
f.add_arc('2', '2', (letter), ('C'))
f.add_arc('3', '2', (letter), ('C'))
# Evaluate it on some example words (.join is the reverse of split(), it joins two items together)
# Outputs 'vwl'
# print(''.join(f.transduce(['v', 'o', 'w', 'e', 'l'])))
# without join : output is a separate characters in a list
print(f.transduce(['v', 'o', 'w', 'e', 'l', '#']))
# Outputs 'xcptn'
print(''.join(f.transduce('e x c e p t i o n'.split())))
# Outputs 'cnsnnt'
print(''.join(f.transduce('c o n s o n a n t'.split())))
disp = FSTDisplay(f)
# disp.transduce("e x c e p t i o n".split())
# disp.loop()
The code is fine and I get the output below when I run it using PyCharm:
The only problem is why it didn't show me the state transition diagram? I manually add the nltk_cont folder in nltk folder which located in site-packages but still it didn't work. Can someone help me?
Below is the path of the folder:
It should be like this: