【问题标题】:Find entries of one text file in another file in python在python中的另一个文件中查找一个文本文件的条目
【发布时间】:2016-06-22 11:55:52
【问题描述】:

我有两个文件。文件 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  

【问题讨论】:

  • 下一个可能不在。
  • 它就在那里。我已添加自己进行测试。
  • 这个任务可以通过grep来完成,如下:grep -f fileA fileB。最好的代码是您不必编写的代码。如果你在 Windows 上,你可以试试Get-Content fileB | Select-String -Pattern (Get-Content fileA)

标签: python string compare readfile


【解决方案1】:

去除换行符的条目

当您读取行时,Python 包含换行符 - 您的第一个条目被读取为 1223232\n。去掉换行符就可以了。

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

【讨论】:

    【解决方案2】:

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

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

    如果它们都具有相同的行,它将以集合的形式返回。

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

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

    【讨论】:

    • 名称“检查”是错字。
    • 您的解决方案仍然无法解决我的问题。请再次检查问题。我也添加了文件数据。
    • 文件 A 中的所有数字都与文件 B 不匹配。此外,如果您尝试匹配所有列出的数字,则需要将 readlines() 更改为 read().split()
    • 数字不匹配,因为这只是一个测试数据。但是让我编辑它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多