分析python中包含转义引号和分隔符的数据



我的数据结构如下:

1661171420, foo="bar", test="This, is a "TEST"", count=5, com="foo, bar=blah"

它总是以unix时间戳开始,但我不知道后面有多少其他字段以及它们是如何调用的。

目标是将其解析为这样的字典:

{"timestamp": 1661171420,
"foo": "bar",
"test": 'This, is a "TEST"',
"count": 5,
"com": "foo, bar=blah"}

我在解析这一点时遇到了困难,尤其是在值中的转义引号和逗号方面。正确解析这个问题的最佳方法是什么?优选地没有任何第三方模块。

如果改变输入数据的格式不是一个选项(JSON更容易处理,但如果它像你说的那样是一个API,那么你可能会陷入困境(,假设文件或多或少遵循给定的结构,以下内容将起作用。我同意,这不是最干净的解决方案,但它确实有效。

import re
d = r'''1661171420, foo="bar", test="This, is a "TEST"", count=5, com="foo, bar=blah", fraction=-0.11'''.replace(r""", "'''")
string_pattern = re.compile(r'''(w+)="([^"]*)"''')
matches = re.finditer(string_pattern, d)
parsed_data = {}
parsed_data['timestamp'] = int(d.partition(", ")[0])
for match in matches:
parsed_data[match.group(1)] = match.group(2).replace("'''", """)
number_pattern = re.compile(r'''(w+)=([+-]?d+(?:.d+)?)''')
matches = re.finditer(number_pattern, d)
for match in matches:
try:
parsed_data[match.group(1)] = int(match.group(2))
except ValueError:
parsed_data[match.group(1)] = float(match.group(2))
print(parsed_data)

最新更新