我是Python新手,遇到了一个我无法解决的问题。JSON,Python中的列表和递归
我已经从JSON解码下面的分析树到以下列表。
>>> 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']]]]], ['.', '.']]]
使用递归函数,我已能够获得包含终端单词的列表。
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'.]
现在我需要更换符合某些标准在原树的话,让我得到这样的:
['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']]]]], ['.', '.']]]
我曾尝试以下功能,但我不能向上传播替代品,所以我总是得到相同的原始树。
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)
我希望在如何实现结果的一些提示。先谢谢你。
@Daniel Roseman感谢您的编辑! – Serge