2013-04-04 75 views
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) 

回答

0

你根本没有写信给文件。你应该重新打开你的文件(或打开另一个文件)。你可以这样说:

with codecs.open('result_file.json', 'w', 'utf-8') as output_file: 
    output_file.write(json.dumps(your_data)) 

你也应该关闭文件描述符你的open()打开

fd = open(filename, filemode) 
# do your stuff to fd 
fd.close() 

备用语法,这(+的python2.5)是

with open(filename, 'r') as fd: 
    lines = fd.readlines() # or anything else to do with fd 

还有一件事 - 你正在用.readline()方法阅读一行。

+0

对不起,我发布的代码只是读取一个分析树来测试我的代码,我也没有输出任何东西,因为我不知道如何替换子列表中的单词。 – user2183811 2013-04-05 02:02:12

+0

我觉得主要的问题有点怪异。想一想 - 你使用的是正确的数据吗?你的输入数据是二叉树吗?如果是这样,您可以使用较少的冗长表示,例如:http://mail.python.org/pipermail/tutor/2001-May/005456.html – dredozubov 2013-04-05 11:16:15