在 python 中的另一个文件中查找一个文本文件的条目

Find entries of one text file in another file in python

我有两个文件。文件 A 每行都有一些条目,我需要查找是否在文件 B 中找到任何条目。这是我的脚本(使用两个函数):

def readB(x):
 with open('B.txt') as resultFile:
    for line in resultFile:
        if x in line:
            print x


def readA():
 with open('A.txt') as bondNumberFile:
    for line in bondNumberFile:
        readB(line)

readA()

此脚本找到第二个文件中的第一个条目,然后没有找到下一个。这里可能有什么问题?

文件 A 如下所示:

122323 
812549
232335
921020

文件 B 看起来像这样:

696798  727832  750478  784201  812549  838916  870906  890988  921020  
697506  727874  751037  784955  813096  838978  872494  891368  921789  
696798  727832  750478  784201  812549  838916  870906  890988  921020  
697506  727874  751037  784955  813096  838978  872494  891368  921789  

您不一定需要定义函数来执行此操作

with open('a.txt') as a, open('b.txt') as b:
    result = set(a.readlines()) & set(b.readlines())

如果他们有相同的线,它将 return 他们在一组。

如果你真的想要一个函数,你可以这样写

def compare(file1: str, file2: str) -> set:
    with open(file1) as f1, open(file2) as f2:
        return set(f1.readlines()) & set(f2.readlines())

去掉条目的换行符

Python 在您阅读行时包含换行符 - 您的第一个条目被读作 1223232\n。去掉换行符就可以了。

def readA():
    with open('A.txt') as bondNumberFile:
        for line in bondNumberFile:
            readB(line.rstrip())