I am new to Python and have come across a problem I cannot solve.
I have decoded the following parse tree from JSON to the following list.
>>> tree
['S', ['NP', ['DET', 'There']], ['S', ['VP', ['VERB', 'is'], ['VP', ['NP', ['DET', 'no'], ['NOUN', 'asbestos']], ['VP', ['PP', ['ADP', 'in'], ['NP', ['PRON', 'our'], ['NOUN', 'products']]], ['ADVP', ['ADV', 'now']]]]], ['.', '.']]]
Using a recursive function, I have been able to obtain a list containing the terminal words.
def explorer(tree):
for sub in tree[1:]:
if(type(sub) == str):
allwords.append(sub)
else:
explorer(sub)
>>> allwords
['There', 'is', 'no', 'asbestos', 'in', 'our', 'products', 'no'.]
Now I need to replace the words that meet some criteria in the original tree, so that I get something like this:
['S', ['NP', ['DET', 'There']], ['S', ['VP', ['VERB', 'is'], ['VP', ['NP', ['DET', 'no'], ['NOUN', '_REPLACED_']], ['VP', ['PP', ['ADP', 'in'], ['NP', ['PRON', 'our'], ['NOUN', 'products']]], ['ADVP', ['ADV', 'now']]]]], ['.', '.']]]
I have tried the following function, but I am unable to propagate the replacements upwards, so I always get the same old original tree.
def replacer(tree):
string=[]
for sub in tree[1:]:
if(type(sub) == str):
if #'condition is true':
sub="_REPLACE_"
return sub
else: return sub
else:
string.extend(replacer(sub))
print(string)
I would appreciate some hint in how to achieve the results. Thank you in advance.