如何将文件与另一个文件中的模式进行比较
带模式的文件(patterns.txt)
pattern1
pattern2
pattern3
文件(file.txt)
something1
something3
pattern1
something4
something5
pattern2
something6
pattern3
something7
脚本
#!/usr/bin/python
import sys
patternFile = sys.argv[1]
fileName = sys.argv[2]
with open(patternFile, 'r') as file_open:
for pattern in file_open:
with open(fileName, 'r') as file_to_compare:
if pattern in file_to_compare:
print pattern
它不起作用;我错过了什么?
./ searchPattern.py patterns.txt file.txt
由于
答案 0 :(得分:0)
你有没有尝试过这样的事情:
patternList = open(patternFile, 'r')
patternListLines = patternList.readlines()
fileTXT = open(fileName , 'r')
def checkPattern(patternList ,x):
if x in patternList:
return True
matchPattern=[x for x in fileTXT.readlines() if checkPattern(patternList, x)]
答案 1 :(得分:0)
我没有,但它现在正在运作。
我在file_to_compare中为添加了:
现在工作了!
Sctipt:
#!/usr/bin/python
import sys
patternFile = sys.argv[1]
fileName = sys.argv[2]
with open(patternFile, 'r') as file_open:
for pattern in file_open:
with open(fileName, 'r') as file_to_compare:
for line in file_to_compare:
if pattern in line: print pattern
./searchPattern.py patterns.txt file.txt
pattern1
pattern2
pattern3