我很困在这里。假设我有一个文本文件(示例.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
我现在有一个排除文本文件(排除.txt),其中包含要不打印的部分行:
Generic
common
don't care about
这个想法是我想打开示例.txt文件,打开排除项.txt文件,然后打印示例中不包含任何行.txt排除项中的任何行.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,如果文本文件中的一行包含排除项中的任何行,请不要打印它。
你让它变得不必要地复杂:
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
似乎你想要:
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
这可能可以使用一些魔术语法进行压缩,但这会更难阅读。根据您的输出需求,您可能需要从文本文件行中删除。