markkillah markkillah - 1 year ago 65
Python Question

How to properly set fst rules

I got in touch with tranducers and python, so i use default FST library. For example, I have a list

. I need to replace
if it is followed by
. I make following rules, but it works only if
is between
and only with this length of array.

from fst import fst
list = ['a','b','c']
t = fst.FST('example')
for i in range(0,len(list)):

t.initial_state = '0'

print t.transduce(list)

I got

I need to be able replace
wherever it is.
e.g. replace
when followed by

['m','r','b','l'] => ['m','r','o','l']
['m','b','l'] => ['m','o','l']
['b','l','o'] => ['o','l','o']

Please help me, thanks!

Answer Source

Consider this function...

lists = [['m','r','b','l'], 

def change(list_, find_this, followed_by, replace_to):
    return_list = list_.copy()
    idx = list_.index(find_this)
    if list_[idx+1] == followed_by:
        return_list = list_.copy()
        return_list[idx] = replace_to
    return return_list

for lst in lists:
    print(change(lst, 'b', 'l', 'o'))

''' output:
['m', 'r', 'o', 'l']
['m', 'o', 'l']
['o', 'l', 'o']
['b', 'm', 'o']

You should add other pertinent validations, though.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download