我是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