我对 python 不是很有经验我有一个解析树列表结构,其中包含一个列表,其中包含子列表中的子列表等等。我需要用RARE替换树中的一些单词。我写了一个递归程序,可以让我找到单词并确定它们是否满足替换条件。我被困在如何在原始文件中实际替换它们。
import json
s_tring=json.loads(open("tree.example").readline())
def word_find(s_tring):
for item in s_tring:
#check if end of tree, always with character "."
if "." in item[0]:
break
else:
#words only appear in sublists of length 2
#some of those are lists of strings ['a','b'] (word is 'b')
#others are list with sublists ['a',['b','c']] (word is 'c')
if len(item)==2 and type(item)==list:
if type(item[1]) == list:
word-to_evaluate = item[1][1]
#need to replace it in tree.example if condition met
else:
word_to_evaluate = item[1]
#need to replace it in tree.example if condition met
else:
#recursive call to continue drilling down the tree
if len(item)==3:
word_find(item)
return
word_find(s_tring)