繁体   English   中英

如何解析 Python 中特定 substring 旁边的值

[英]How to parse a value next to a specific substring in Python

我有一个日志文件,其中包含格式如下所示的行。 我想解析子字符串element=(string)time=(guint64)ts=(guint64)旁边的值,并将它们保存到一个列表中,该列表将包含每行的单独列表:

0:00:00.336212023 62327 0x55f5ca5174a0 TRACE             GST_TRACER :0:: element-latency, element-id=(string)0x55f5ca532a60, element=(string)rawvideoparse0, src=(string)src, time=(guint64)852315, ts=(guint64)336203035;
0:00:00.336866520 62327 0x55f5ca5176d0 TRACE             GST_TRACER :0:: element-latency, element-id=(string)0x55f5ca53f860, element=(string)nvh264enc0, src=(string)src, time=(guint64)6403181, ts=(guint64)336845676;

最终的 output 将如下所示: [['rawvideoparse0', 852315, 336203035], ['nvh264enc0', 6403181, 336845676]]

我可能应该使用 Python 的字符串拆分或分区方法来获取每一行中的相关部分,但我无法提出一个可以概括为我正在搜索的值的简短解决方案。 我也不知道如何处理 values elementtime以逗号结尾而ts以分号结尾的事实(没有为这两种情况编写单独的条件)。 如何使用 Python 中的字符串操作方法来实现这一点?

这是使用一系列拆分命令的可能解决方案:

output = []
with open("log.txt") as f:
    for line in f:
        values = []
        line = line.split("element=(string)", 1)[1]
        values.append(line.split(",", 1)[0])
        line = line.split("time=(guint64)", 1)[1]
        values.append(int(line.split(",", 1)[0]))
        line = line.split("ts=(guint64)", 1)[1]
        values.append(int(line.split(";", 1)[0]))
        output.append(values)

正则表达式是为此而设计的:

lines = """
0:00:00.336212023 62327 0x55f5ca5174a0 TRACE             GST_TRACER :0:: element-latency, element-id=(string)0x55f5ca532a60, element=(string)rawvideoparse0, src=(string)src, time=(guint64)852315, ts=(guint64)336203035;
0:00:00.336866520 62327 0x55f5ca5176d0 TRACE             GST_TRACER :0:: element-latency, element-id=(string)0x55f5ca53f860, element=(string)nvh264enc0, src=(string)src, time=(guint64)6403181, ts=(guint64)336845676;
"""

import re

pattern = re.compile(".*element-id=\\(string\\)(?P<elt_id>.*), element=\\(string\\)(?P<elt>.*), src=\\(string\\)(?P<src>.*), time=\\(guint64\\)(?P<time>.*), ts=\\(guint64\\)(?P<ts>.*);")
for l in lines.splitlines():
    match = pattern.match(l)
    if match:
        results = match.groupdict()
        print(results)

产生以下字典(请注意,捕获的组已在上面的正则表达式中使用(?P<name>...) ,这就是我们有这些名称的原因):

{'elt_id': '0x55f5ca532a60', 'elt': 'rawvideoparse0', 'src': 'src', 'time': '852315', 'ts': '336203035'}
{'elt_id': '0x55f5ca53f860', 'elt': 'nvh264enc0', 'src': 'src', 'time': '6403181', 'ts': '336845676'}

您可以使这个正则表达式模式更加通用,因为所有元素共享一个共同的结构<name>=(<type>)<value>

pattern2 = re.compile("(?P<name>[^,;\s]*)=\\((?P<type>[^,;]*)\\)(?P<value>[^,;]*)")
for l in lines.splitlines():
    all_interesting_items = pattern2.findall(l)
    print(all_interesting_items)

它产生:

[]
[('element-id', 'string', '0x55f5ca532a60'), ('element', 'string', 'rawvideoparse0'), ('src', 'string', 'src'), ('time', 'guint64', '852315'), ('ts', 'guint64', '336203035')]
[('element-id', 'string', '0x55f5ca53f860'), ('element', 'string', 'nvh264enc0'), ('src', 'string', 'src'), ('time', 'guint64', '6403181'), ('ts', 'guint64', '336845676')]

请注意,在所有情况下, https://regex101.com/都是您调试正则表达式的朋友:)

这不是最快的解决方案,但这可能是我为了可读性而编写它的方式。

# create empty list for output
list_final_output = []

# filter substrings
list_filter = ['element=(string)', 'time=(guint64)', 'ts=(guint64)']

# open the log file and read in the lines as a list of strings
with open('so_58272709.log', 'r') as f_log:
    string_example = f_log.read().splitlines()
print(f'string_example: \n{string_example}\n')

# loop through each line in the list of strings
for each_line in string_example:

    # split each line by comma
    list_split_line = each_line.split(',')

    # loop through each filter substring, include filter
    filter_string = [x for x in list_split_line if (list_filter[0] in x
                                                    or list_filter[1] in x
                                                    or list_filter[2] in x
                                                   )]

    # remove the substring
    filter_string = [x.replace(list_filter[0], '') for x in filter_string]
    filter_string = [x.replace(list_filter[1], '') for x in filter_string]
    filter_string = [x.replace(list_filter[2], '') for x in filter_string]

    # store results of each for-loop
    list_final_output.append(filter_string)

# print final output
print(f'list_final_output: \n{list_final_output}\n')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM