Python 替换子列表中的单词
我对python不是很有经验 我有一个解析树列表结构,它包含一个在子列表中包含子列表的列表,以此类推。 我需要用“稀有”替换树上的一些单词。 我已经编写了一个递归过程,它允许我找到单词并确定它们是否满足替换条件。 我被困在如何在原始文件中实际替换它们Python 替换子列表中的单词,python,parsing,replace,sublist,Python,Parsing,Replace,Sublist,我对python不是很有经验 我有一个解析树列表结构,它包含一个在子列表中包含子列表的列表,以此类推。 我需要用“稀有”替换树上的一些单词。 我已经编写了一个递归过程,它允许我找到单词并确定它们是否满足替换条件。 我被困在如何在原始文件中实际替换它们 import json s_tring=json.loads(open("tree.example").readline()) def word_find(s_tring): for item in s_tring: #ch
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)
你根本没有在写文件。您应该重新打开文件进行写入(或打开另一个文件)。您可以这样做:
with codecs.open('result_file.json', 'w', 'utf-8') as output_file:
output_file.write(json.dumps(your_data))
此外,还应该关闭用open()打开的文件描述符
这个(python2.5+)的替代语法是
还有一件事-您使用.readline()方法只读取了一行 抱歉,我发布的代码只是读取一个解析树来测试我的代码,而且我还没有输出任何东西,因为我不知道如何替换子列表中的单词。我发现主要问题有点奇怪。想想看,你使用的数据是否正确?您的输入数据是二叉树吗?如果是,则可以使用较少的块状表示,例如:
fd = open(filename, filemode)
# do your stuff to fd
fd.close()
with open(filename, 'r') as fd:
lines = fd.readlines() # or anything else to do with fd