Python startswith 函数:打印非部分匹配的行

Python startswith function: printing non partially matched lines

您好,我想使用 startswith 函数打印出 fileY.txt 中的行,这些行 NOT 与 [=16] 中的行部分匹配=]

在下面的脚本中,我使用 fileX.txtfileY.txt 作为列表。然后,我使用 startswith 函数搜索 fileX.txtfileY.txt 的部分匹配项。

接下来,我尝试打印 NOT 部分匹配 fileX.txtfileY.txt 的行。但是脚本只打印 fileY.txt

中的最后一行

任何帮助将不胜感激(我不介意我是否必须使用像 sed 这样的辅助应用程序)

来源:

#load lines from file into lists
lines1 = [line1.rstrip('\n') for line1 in open('fileX.txt')]
lines2 = [line2.rstrip('\n') for line2 in open('fileY.txt')]

#set lines
set_of_lines1 = set(lines1)
set_of_lines2 = set(lines2)

#set common
common = set_of_lines1 & set_of_lines2

#return lines which partially match as variable e
[e for e in lines1 if e.startswith(tuple(lines2))]

#minus partially matched lines from fileY.txt
difference = set_of_lines2 - e

#print the non matching lines
for color in difference:
   print 'The color prefix ' + color + ' does not exist in the list'

fileX.txt:

blue
green
red

fileY.txt:

blu
gre
re
whi
oran

我想要的:

C:\Users\Foo\Bar\Python\Test\>C:\python27\python Test.py
The color prefix whi does not exist in the list
The color prefix oran does not exist in the list

Press any key to continue . . .

第一个问题是这一行:

[e for e in lines1 if e.startswith(tuple(lines2))]

它构建了一个部分匹配的列表,然后将其丢弃。您所保留的只是 e 的值,它已从列表理解中泄漏出来(并且在 Python 3 中会给您一个未定义的值错误)。您需要:

partial_match = [e for e in lines1 if e.startswith(tuple(lines2))]

这给我们带来了第二个问题。如果你打印出 partial_match,你会看到它包含 ['blue', 'green', 'red'] 并且我认为你期望它包含 ['blu', 'gre', 're'],因为你试图在它和 [= 之间做一个设置差异19=].

由于您的问题围绕列表理解展开,我建议您将其展开到一个循环中,您可以在其中打印出中间值,这样您就可以看到正在发生的事情并获得正确的逻辑。如果你真的想要一个单行的,你可以稍后重写它。

像这样:

matches = []
for prefix in lines2:
    for colour in lines1:
        if colour.startswith(prefix):
            matches.append(prefix)

matches 现在将包含 ['blu', 'gre', 're']。现在报告不匹配的前缀。

for nomatch in set(lines2) - set(matches):
    print "The color prefix %r does not exist in the list" % nomatch

这将为您提供输出:

The color prefix 'whi' does not exist in the list
The color prefix 'oran' does not exist in the list