Python逐行比较2个文件。如果文件1中的行与文件2中的行不一致,则打印
我一直在使用下一个代码逐行读取file1,并搜索file2的任何一行是否包含这一行。然后打印出来Python逐行比较2个文件。如果文件1中的行与文件2中的行不一致,则打印,python,string,compare,Python,String,Compare,我一直在使用下一个代码逐行读取file1,并搜索file2的任何一行是否包含这一行。然后打印出来 import os import sys def extractAllLine(str2Search): with open("/path/to/dump/file/Dump.txt") as All_file: for line in All_file: if str2Search in line:
import os
import sys
def extractAllLine(str2Search):
with open("/path/to/dump/file/Dump.txt") as All_file:
for line in All_file:
if str2Search in line:
print line,
def extractFilter():
with open("/path/to/filter/Filter.txt") as filter_file:
for line in filter_file:
filterstring = line.rstrip()
extractAllLine(filterstring)
if __name__ == '__main__':
extractFilter()
Dump.txt
brandon richardson
kian dixon
ashton harris
jamie hunt
reece thomas
kendrick battle
tucker blankenship
jamie holman
mitchell douglas
ace holder
Filter.txt
jamie
dixon
ace
运行代码将导致:
jamie hunt
jamie holman
kian dixon
ace holder
现在我想做相反的事情,我想打印文件2中不包含文件1中的行的行。
例如:
Dump.txt和Filter.txt,保持不变。
但希望的结果是:
brandon richardson
ashton harris
reece thomas
kendrick battle
tucker blankenship
mitchell douglas
我尝试在def extracAllLine中更改“如果”:
if str2Search **not** in line:
print line,
但它不起作用。
如何将其更改为false,以便获得想要的结果?在
filter.txt
中不搜索关键字的相反条件应为
jamie not in line and dixon not in line and ace not in line ...
所以你应该先得到所有这些关键词
这里有一个简单的参考例子,你可以用自己的方式来做
import os
import sys
def extractAllLine(strsNot2Search):
with open("/path/to/filter/Dump.txt") as All_file:
for line in All_file:
if not list(filter(lambda str2Search: str2Search in line, strsNot2Search)):
print(line)
def extractFilter():
with open("/path/to/filter/Filter.txt") as filter_file:
filterConditions = [] # collect all your not search conditions here
for line in filter_file:
filterstring = line.rstrip()
filterConditions.append(filterstring)
extractAllLine(filterConditions)
if __name__ == '__main__':
extractFilter()
完美的我认为需要一个“不在”来扭转搜索。但我知道这需要更多的时间。我很好奇你说“按你的方式去做”,有没有其他的解决办法比比较台词更有效?更快的解决方案还是更快的算法?