从python中的字符串消息中提取括号“[]”中指定的数据

2024-03-29 09:33:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从下面的日志消息中提取字段。你知道吗

示例:

Ignoring entry, Affected columns [column1:column2], reason[some reason], Details[some entry details]

我需要提取括号[ ]中为“受影响的列、原因、详细信息”指定的数据

在Python中提取这些字段的有效方法是什么?你知道吗

注意:如果需要,我可以修改日志消息格式。


Tags: columns消息示例详细信息原因somedetails括号
1条回答
网友
1楼 · 发布于 2024-03-29 09:33:56

如果您可以随意更改日志格式,那么使用公共数据格式是最简单的—我建议将JSON用于此类数据。它是结构化的,但足够轻量级,甚至可以从自定义bash脚本编写它。^{} module允许您直接将其转换为本机python对象:

import json  # python has a default parser
# assume this is your log message
log_line = '{"Ignoring entry" : {"Affected columns": [1, 3], "reason" : "some reason", "Details": {}}}'
data = json.loads(log_line)
print("Columns to ignore:", data["Ignoring entry"]["Affected columns"])

如果要使用当前格式,则必须使用str方法或re模块。你知道吗

例如,您可以这样做:

log_msg = "Ignoring entry, Affected columns [column1:column2], reason[some reason], Details[some entry details]"
def parse_log_line(log_line):
  if log_line.startswith("Ignoring entry"):
    log_data = {
    for element in log_line.split(',')[1:]:  # parse all elements but the header
      key, value = element.partition('[')
      if value[-1] != ']':
        raise ValueError('Malformed Content. Expected %r to end with "]"' % element)
      value = value[:-1]
      log_data[key] = value
    return log_data
  raise ValueError('Unrecognized log line type')

许多解析任务最好由^{} module紧凑地处理。它允许您使用正则表达式。它们非常强大,但是如果你不习惯的话,很难维护。在您的情况下,以下操作将起作用:

log_data = {key: value for key, value in re.findall(',\s?(.+?)\s?\[(.+?)\]', log_line)}

重建工作如下:

  • ,一个逗号,用来分隔条目
  • \s*逗号后,下一个元素前的任意空格序列
  • (.+?)任何非空白字符(键,通过'()'捕获)
  • \s*键和值之间的任意空格序列
  • \[文字[
  • (.+?)下一个元素之前的最短的非空白字符序列(通过'()'捕获的值)
  • \]文字]

符号*+?表示“任意”、“多个”和“尽可能少”。你知道吗

相关问题 更多 >