1

我正在尝试解析其中的每一行list.txt,如果没有任何更改(数字) ,请change_list删除整个条目(不仅仅是那个数字)并OUTPUT.txt使用剩余的数字创建一个新文件。

在下面的示例中, 350166 中不存在change_list,因此删除了整行“350882 348521 350166”,仅将其余行添加到 中output.txt

出于某种原因,我似乎没有得到想要的结果。谁能指出哪里出错了?

change_list=[]
def changecheck(change) :
    changelist=['355199','352470','346917','350882','348521']
    if change in changelist:
        return 1
    else:
        return 0


with open('list.txt', 'r') as f:
    for line in f :
        line=line.strip()
        change_line = line
    print "change_line"
    print change_line

for element in change_line:
    change_list = element.split(' ')
    for changeid in change_list:
        print "changeid"
        print changeid
        returnVal = changecheck('changeId')
        if returnVal  == 1:
            #write the whole line to a new file
            with open('output.txt', 'r') as f:
                f.writelines(element)

文件:

list.txt
350882 348521 350166
346917 352470 
355199 

OUTPUT.txt
346917 352470 
355199 
4

1 回答 1

2

Make your changecheck a set, and then build a generator over the input splitting it up into separate numbers, and only include lines in the file where all numbers on the line are in the changecheck..., eg:

changelist = {'355199','352470','346917','350882','348521'}

with open('input') as fin, open('output', 'w') as fout:
    lines = (line.split() for line in fin)
    valid = (' '.join(line) + '\n' for line in lines if all(el in changelist for el in line))
    fout.writelines(valid)
于 2013-06-25T00:32:43.210 回答