Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 Python文件匹配_Python 2.7 - Fatal编程技术网

Python 2.7 Python文件匹配

Python 2.7 Python文件匹配,python-2.7,Python 2.7,目前有一个小任务,我有两个.txt文件,我想找到两个文件中出现的任何匹配的单词,并将结果输出到一个新文件,但是下面的代码只显示空白文件,不知道我需要更改或查看什么 file1 example file2 example 12345 565 543252 54321 ff df 12345 0000 ff f0 11111 理想情况下,由于12345在两个文件中都匹配,因此应将file1中的12345 565行打印到输出文件中 with open(

目前有一个小任务,我有两个.txt文件,我想找到两个文件中出现的任何匹配的单词,并将结果输出到一个新文件,但是下面的代码只显示空白文件,不知道我需要更改或查看什么

file1 example    file2 example
12345 565        543252 
54321 ff df      12345  
0000  ff f0      11111
理想情况下,由于12345在两个文件中都匹配,因此应将file1中的12345 565行打印到输出文件中

with open('Results.txt', 'r') as file1:
    with open('test.txt', 'r') as file2:
        same = set(file1).intersection(file2)

same.discard('\n')

with open('matches.txt', 'w') as file_out:
    for line in same:
        file_out.write(line)

任何帮助都将不胜感激。

您的代码的问题在于
文件1的第一行实际上是:

12345 565
文件2的第二行是:

12345
您的代码将无法工作,因为
intersect
将尝试匹配此不同的行

您可以做的是:

with open('Results.txt', 'r') as file1:
    with open('test.txt', 'r') as file2:
        a = set(x.split()[0] for x in file1)
        b = [x.rstrip() for x in file2]
        same = a.intersection(b)

same.discard('\n')

print same
输出:
set(['12345'])


请注意,此方法仅使用
file1
中的第一列,因此与其他列的任何其他匹配都不起作用。希望这有帮助

非常感谢,效果非常好!出于兴趣,是否可以打印文件1中的整行?i、 e.12345565?