【问题标题】:Python: How to check a text file, compare it to each line in another text file, and print the lines that do not matchPython:如何检查文本文件,将其与另一个文本文件中的每一行进行比较,并打印不匹配的行
【发布时间】:2012-09-25 09:25:36
【问题描述】:

我被困在这里了。假设我有一个如下所示的文本文件 (example.txt):

Generic line 1() 46536.buildsomething  
Generic line 2() 98452.constructsomething  
Something I'm interested in seeing  
Another common line() blablabla abc945  
Yet another common line() runningoutofideashere.923954  
Another line I'm interested in seeing  
Line I don't care about 1() yaddayaddayadda  
Line I don't care about 2() yaddayaddayadda  
Generic line 3() 23485.buildsomething  
Yet some other common line  

我现在有一个排除文本文件 (exclusions.txt),其中包含不打印的部分行:

Generic  
common  
don't care about

我的想法是我要打开 example.txt 文件,打开 excludes.txt 文件,然后打印 example.txt 中不包含 excludes.txt 中任何行的任何行。

到目前为止我所尝试的(没有任何成功):

textfile = open("example.txt", "r")
textfile = textfile.readlines()

exclusionslist = []
exclusions = open("exclusions.txt", "r")
exclusions = exclusions.readlines()
for line in exclusions:
    exclusionslist.append(line.rstrip('\n'))

for excline in exclusions:
    for line in textfile:
        if exline not in line:
            print line

我想我知道问题出在哪里,但我不知道如何解决它。我想我只需要告诉 Python,如果文本文件中的一行在排除项中包含 any 行,请不要打印它。

【问题讨论】:

  • 有问题吗?你有什么问题?
  • 我想我在最后一句话中很好地解释了我的问题,即使它没有问号。有关该问题的解决方案,请参见下面的答案。

标签: python list filter compare


【解决方案1】:

你让它变得不必要地复杂了:

with open("example.txt", "r") as text, open("exclusions.txt", "r") as exc:
    exclusions = [line.rstrip('\n') for line in exc]
    for line in text:
        if not any(exclusion in line for exclusion in exclusions):
            print line

【讨论】:

  • with open() 位似乎对我的 Python 不太满意(使用 2.5,最初可能应该提到这一点),但它的其余部分工作得非常好。感谢您的快速帮助!
  • @user1719723:如果可以的话,升级到 Python 2.7(或者如果你敢的话,升级到 3.3),如果你不能这样做,在你的脚本顶部添加 from __future__ import with_statement,不用担心即使您的脚本中止,也必须再次关闭文件。不过,我认为在 Python 2.5 中,您将不得不使用两个嵌套的 with 块;使用逗号的连接可能没有被反向移植:stackoverflow.com/questions/893333/…
  • 使用with 代替try:finally 有什么陷阱吗?
  • @MarkRibau:我不这么认为;我发现with 的使用更清晰、更容易。
  • @TimPietzcker 似乎with 中使用的文件仅在下一次垃圾回收时才关闭?至少这似乎是我们所看到的行为。尝试在 a with 块之后重用文件,间歇性地失败,但在 with 块之后执行显式 gc.collect() 使其停止失败。 [独立 Python v2.7.1,SCons v2.1.0]
【解决方案2】:

好像你想要的:

textfile = open("example.txt", "r")
textfilelines = textfile.readlines()

exclusions = open("exclusions.txt", "r")
exclusionlines = exclusions.readlines()
for x in range(len(exclusionlines)):
    exclusionlines[x] = exclusionlines[x].strip("\n")

for line in textfilelines:
    found = False
    for exclude in exclusionlines:
        if exclude in line:
            found = True
    if not found:
        print line

这可能可以使用一些神奇的语法进行压缩,但这会更难阅读。根据您的输出需求,您可能需要从 textfilelines 中删除 \n。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-29
    • 2020-06-12
    • 2020-08-20
    • 1970-01-01
    相关资源
    最近更新 更多