【问题标题】:File parsing in PythonPython中的文件解析
【发布时间】:2016-03-18 11:08:19
【问题描述】:

我已经阅读了一些关于在 Python 中解析文件的信息,但我现在还不清楚,所以我需要一些帮助。

我有一个日志文件,其中包含具有特定标记的字符串,如警告、调试等。 我想把它们都放到不同的列表中,以便以后使用。 所以基本上据我了解,我需要使用正则表达式来做到这一点。我现在拥有的代码。

部分代码将帮助您了解我要放置的位置和内容:

message = ('CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG', 'AUDIT', 'TRACE')
crit, err, warn, info, deb, aud, tra = [], [], [], [], [], [], []
error = (crit, err, warn, info, deb, aud, tra)

这是解析器代码:

with open(log, 'r+') as f:
    lines = f.readlines()

    for line in lines:
        for i in range(len(message)):
            match = re.search(message[i], line)
            if match:
                new_line = match.group()
                error[i].append(new_line)

所以“for line in lines”中的行本身可以完美抓取,但是当我进入“for i in range(len(message)):”并尝试打印匹配时 - 它给了我一个对象并且 new_line 仅附加“警告”等词。所以不是整行,但我需要它没有任何削减。

提前致谢!

【问题讨论】:

  • 如果您需要整行,为什么不使用new_line = line 而不是match.group()
  • 是的,我想通了。我需要将行为更改为:for line in lines: for i in range(len(message)): if re.search(message[i], line): error[i].append(line)跨度>
  • 如果您只是想检查是否可以从line 找到message[i],则可以通过if message[i] in line: 完成,而无需使用正则表达式
  • 我也试试,谢谢!

标签: python regex parsing logging


【解决方案1】:

如果您想要该行,请附加该行:error[i].append(line) 而不是 match.group()

【讨论】:

    猜你喜欢
    • 2013-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多