【发布时间】:2018-08-05 15:51:12
【问题描述】:
我需要比较前两列的两个文件,并选择匹配的具有第二个文件的附加信息的文件,例如;
输入1:
0 1
2 4
5 6
输入2:
2 4 xyz
5 4 asv
0 1 qwe
输出是
2 4 xyz
0 1 qwe
我在 python 上试过,但不能正常工作;就像如果第一列有更多 1 它不能给出正确的输出
#!/usr/bin/python
import sys
f1 = 'file1.txt'
f2 = 'file2.txt'
if len(sys.argv) == 3:
f1 = sys.argv[1]
f2 = sys.argv[2]
with open(f1) as file_1, open('out.txt', 'w') as of:
for l1 in file_1:
col_of_f1 = int(l1.split()[0])
with open(f2) as file_2:
for l2 in file_2:
col_of_f2 = l2.split()
if len(col_of_f2) < 1:
break
col_of_f2 = int(col_of_f2[0])
if col_of_f1 == col_of_f2:
of.write(l2)
break
【问题讨论】:
-
还有......你尝试了什么,它是如何失败的?
-
为什么
python和perl标记霍夫?你能给我们一些代码以便我们帮助你吗? -
对于 python 我试过这个但不能正常工作 f1 = 'file1.txt' f2 = 'file2.txt' if len(sys.argv) == 3: f1 = sys.argv[1] f2 = sys.argv[2] with open(f1) as file_1, open('out.txt', 'w') as of: for l1 in file_1: col_of_f1 = int(l1.split()[0]) with open(f2) as file_2: for l2 in file_2: col_of_f2 = l2.split() if len(col_of_f2)