我有两个文件。一个有两列,ref.txt。另一个有三列,file.txt。
在 ref.txt 中,
1 2
2 3
3 5
在文件.txt中,
1 2 4 <---here matching
3 4 5
6 9 4
2 3 10 <---here matching
4 7 9
3 5 7 <---here matching
我想比较每个文件的两列,然后只打印 file.txt 中与 ref.txt 匹配的行。
所以,输出应该是,
1 2 4
2 3 10
3 5 7
我以为两个字典比较像,
mydict = {}
mydict1 = {}
with open('ref.txt') as f1:
for line in f1:
key, key1 = line.split()
sp1 = mydict[key, key1]
with open('file.txt') as f2:
for lines in f2:
item1, item2, value = lines.split()
sp2 = mydict1[item1, item2]
if sp1 == sp2:
print value
如何将两个文件与字典或其他文件进行适当比较?
我找到了一些 perl 和 python 代码来解决两个文件中相同数量的列。
在我的例子中,一个文件有两列,另一个文件有三列。
如何比较两个文件并只打印匹配的值?
最佳答案
这是另一种选择:
use strict;
use warnings;
my $file = pop;
my %hash = map { chomp; $_ => 1 } <>;
push @ARGV, $file;
while (<>) {
print if /^(\d+\s+\d+)/ and $hash{$1};
}
用法:perl script.pl ref.txt file.txt [>outFile]
最后一个可选参数将输出定向到文件。
数据集的输出:
1 2 4
2 3 10
3 5 7
希望这对您有所帮助!
关于python - 如何比较两个文件并打印仅与第一个文件匹配的第二个文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20155446/