栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

这应该使您入门不错:

infile = r"D:documents and SettingsxxxxDesktoptest_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) breakprint(important)

它绝不是完美的,例如,没有异常处理或模式匹配,但是您可以很容易地将它们添加到其中。查看正则表达式,这可能比词组匹配更好。如果文件很大,请逐行读取它,以避免出现MemoryError。

输入文件:

This line is super important!don't need this one...keep me!bla blanot botheredALWAYS include this test line

输出:

['This line is super important!n', 'keep me!n', 'ALWAYS include this test line']

注意:这是Python 3.3。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668250.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号