![](/img/trans.png)
[英]How to check each line of a text file for a string and print all lines with occurrences of that word to a new text file?
[英]Python: How to check a text file, compare it to each line in another text file, and print the lines that do not match
我被困在这里了。 假设我有一个文本文件(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文件,打开exclusions.txt文件,然后打印example.txt中不包含exclusions.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
这可能可以使用一些神奇的语法进行压缩,但这会更难阅读。 根据您的输出需求,您可能需要从文本文件中删除\\ n。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.