这应该使您入门不错:
infile = r"D:\Documents and Settings\xxxx\Desktop\test_log.txt"
important = []
keep_phrases = ["test",
"important",
"keep me"]
with open(infile) as f:
f = f.readlines()
for line in f:
for phrase in keep_phrases:
if phrase in line:
important.append(line)
break
print(important)
它绝不是完美的,例如,没有异常处理或模式匹配,但是您可以很容易地将它们添加到其中。查看正则表达式,这可能比词组匹配更好。如果文件很大,请逐行读取它,以避免出现MemoryError。
输入文件:
This line is super important!
don't need this one...
keep me!
bla bla
not bothered
ALWAYS include this test line
输出:
['This line is super important!\n', 'keep me!\n', 'ALWAYS include this test line']
注意:这是Python 3.3。