gpt4 book ai didi

python - 如何在 Python 中解析特定子字符串旁边的值

转载 作者:行者123 更新时间:2023-12-01 00:29:43 32 4
gpt4 key购买 nike

我有一个日志文件,其中包含格式如下所示的行。我想解析子字符串 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;

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

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

最佳答案

正则表达式的目的是:

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'}

您可以使这个正则表达式模式更加通用,因为所有元素共享一个公共(public)结构 <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/ 都是您调试正则表达式的 friend :)

关于python - 如何在 Python 中解析特定子字符串旁边的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58272709/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com