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)
4

1 に答える 1

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

もう 1 つ - .readline() メソッドで 1 行だけを読んでいます。

于 2013-04-04T16:29:29.533 に答える