0
我对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)
对不起,我发布的代码只是读取一个分析树来测试我的代码,我也没有输出任何东西,因为我不知道如何替换子列表中的单词。 – user2183811 2013-04-05 02:02:12
我觉得主要的问题有点怪异。想一想 - 你使用的是正确的数据吗?你的输入数据是二叉树吗?如果是这样,您可以使用较少的冗长表示,例如:http://mail.python.org/pipermail/tutor/2001-May/005456.html – dredozubov 2013-04-05 11:16:15