您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python读取日志文件并获取包含特定单词的行

Python读取日志文件并获取包含特定单词的行

这应该使您入门不错:

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。

python 2022/1/1 18:30:23 有200人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶