【发布时间】:2011-10-02 21:59:15
【问题描述】:
我有 2 个制表符分隔的文件 例如:
文件1:
12 23 43 34
433 435 76 76
文件2:
123 324 53 65
12 457 54 32
我想遍历这两个文件,将 file1 的每一行与 file2 进行比较,反之亦然。 例如,如果 file1 中第 1 行的第 1 个编号与文件 2 中第 2 行的第 1 个编号相同: 我想从 file1 的第一行放入一个名为 output 的文件中。 然后我想将 file1 中在文件 2 中找不到匹配项的所有行放入新文件中 以及 file2 中在新文件中的 file1 中未找到匹配项的所有行。
到目前为止,我已经能够找到匹配的行并将它们放入一个文件中,但我无法将不匹配的行放入 2 个单独的文件中。
one=open(file1, 'r').readlines()
two=open(file2, 'r').readlines()
output=open('output.txt', 'w')
count=0
list1=[] #list for lines in file1 that didn't find a match
list2=[] #list for lines in file2 that didn't find a match
for i in one:
for j in two:
columns1=i.strip().split('\t')
num1=int(columns1[0])
columns2=j.strip().split('\t')
num2=int(columns2[0])
if num1==num2:
count+=1
output.write(i+j)
else:
list1.append(i)
list2.append(j)
我在这里遇到的问题是 else 部分。 谁能告诉我正确和更好的方法,我将不胜感激。
编辑:感谢大家的快速回复 我要寻找的 3 个输出是:
Output_file1: #2个文件的匹配结果
12 23 43 34 #line from file1
12 457 54 32 #line from file2
Output_file2: #lines from the first file that didn't find a match
433 435 76 76
Output_file3: #lines from the second file that didn't find a match
123 324 53 65
【问题讨论】:
-
第一个文件第一行的第一个值和第二个文件第二行的第一个值?
-
要了解您要执行的操作的逻辑,您能否为上面列出的两个输入文件提供您想要的三个输出文件?
-
@Artsiom Rudzenka:对不起,我想说的是,在我给出的示例中,这是定义匹配的条件或逻辑。