0

我有 2 个文本文件,从中我将 txt1 的第二列与 txt2 的第一列匹配|,好吧,我只是在下面提到它,如果它们相同,我会输出,连同它的描述,一切都很好,但我没有'没有得到new line discription输出,它只是显示了它的第一行。

这是txt1.txt的内容

E5 E7 Bat

这是txt2.txt的内容:

?E7|E5
Addsadsadsadsadsadsdasd
Sdsdfsdfdsfdsfdfdsfdsfd
AasadsaddccxcvcsAAGCAGT

这是我正在使用的代码

with open('txt1.txt', 'rb') as file1:
    #file1_data = dict(line.split()[1] for line in file1 if line.strip())
    file1_data = [line.split()[1] for line in file1 if line.strip()]
#print file1_data
with open('txt2.txt', 'rb') as file2, open('output.txt', 'wb') as outputfile:
    output = ""
    file2lines = file2.readlines()
    for i in range(len(file2lines)):
        line = file2lines[i]
        if line[0] == '?':
            row = line.strip().split('|')
            key = row[0][1:]
            if key in file1_data:
                output += line + "\t" + file2lines[i+1]
    outputfile.write(output)
outputfile.close()

Getting output

?E7|E5
Addsadsadsadsadsadsdasd

Required output

?E7|E5
Addsadsadsadsadsadsdasd
Sdsdfsdfdsfdsfdfdsfdsfd
AasadsaddccxcvcsAAGCAGT
4

1 回答 1

1

我认为您需要一些状态处理-“在匹配块中”/“不在匹配块中”。我已经重写了你算法的第二部分:

with open('txt2.txt', 'rb') as file2, open('output.txt', 'wb') as outputfile:
    output = []
    do_block = False
    for line in file2:
        line = line.rstrip()
        if not line: continue
        if line[0] == '?':
            key = line.strip().split('|')[0][1:]
            do_block = key in file1_data
        if do_block:
            output.append(line)
    outputfile.write("\n".join(output))
于 2013-05-12T20:36:03.630 回答