gpt4 book ai didi

python - 将 Erlang 数据解析为 Python 字典

转载 作者:行者123 更新时间:2023-12-02 12:38:10 24 4
gpt4 key购买 nike

我有一个 erlang 脚本,我想从中获取一些数据并将其存储在 python 字典中。解析脚本来获取字符串很容易,如下所示:

    {userdata,
[{tags,
[#dt{number=111},
#mp{id='X23.W'}]},
{log,
'LG22'},
{instruction,
"String that can contain characters like -, _ or numbers"}
]
}.

期望的结果:

userdata = {"tags": {"dt": {"number": 111}, "mp": {"id": "X23.W"}},
"log": "LG22",
"instruction": "String that can contain characters like -, _ or numbers"}
# "#" mark for data in "tags" is not required in this structure.
# Also value for "tags" can be any iterable structure: tuple, list or dictionary.

但我不知道如何将这些数据传输到Python字典中。我的第一个想法是使用 json.loads ,但它需要许多修改(将单词放入引号中,用“:”替换“,”等等)。

此外,用户数据中的键不限于某个池。在这种情况下,有“标签”、“日志”和“指令”,但可以有更多,例如。 “口号”、“ID”等另外,我不确定顺序。我假设 key 可以按随机顺序出现。

我的代码(它不适用于id='X23.W',因此我从输入中删除了“.”):

import re
import json
in_ = """{userdata, [{tags, [#dt{number=111}, #mp{id='X23W'}]}, {log, 'LG22'}, {instruction, "String that can contain characters like -, _ or numbers"}]}"""

buff = in_.replace("{userdata, [", "")[:-2]

re_helper = re.compile(r"(#\w+)")
buff = re_helper.sub(r'\1:', buff)

partition = buff.partition("instruction")
section_to_replace = partition[0]
replacer = re.compile(r"(\w+)")
match = replacer.sub(r'"\1"', section_to_replace)
buff = ''.join([match, '"instruction"', partition[2]])
buff = buff.replace("#", "")
buff = buff.replace('",', '":')

buff = buff.replace("}, {", "}, \n{")
buff = buff.replace("=", ":")
buff = buff.replace("'", "")
temp = buff.split("\n")
userdata = {}
buff = temp[0][:-2]
buff = buff.replace("[", "{")
buff = buff.replace("]", "}")

userdata .update(json.loads(buff))
for i, v in enumerate(temp[1:]):
v = v.strip()
if v.endswith(","):
v = v[:-1]
userdata .update(json.loads(v))

print(userdata)

输出:

{'tags': {'dt': {'number': '111'}, 'mp': {'id': 'X23W'}}, 'instruction': 'String that can contain characters like -, _ or numbers', 'log': 'LG22'}

最佳答案

import json
import re
in_ = """{userdata, [{tags, [#dt{number=111}, #mp{id='X23.W'}]}, {log, 'LG22'}, {instruction, "String that can contain characters like -, _ or numbers"}]}"""


qouted_headers = re.sub(r"\{(\w+),", r'{"\1":', in_)
changed_hashed_list_to_dict = re.sub(r"\[(#.*?)\]", r'{\1}', qouted_headers)

hashed_variables = re.sub(r'#(\w+)', r'"\1":', changed_hashed_list_to_dict)
equality_signes_replaced_and_quoted = re.sub(r'{(\w+)=', r'{"\1":', hashed_variables)
replace_single_qoutes = equality_signes_replaced_and_quoted.replace('\'', '"')

result = json.loads(replace_single_qoutes)
print(result)

产品:

{'userdata': [{'tags': {'dt': {'number': 111}, 'mp': {'id': 'X23.W'}}}, {'log': 'LG22'}, {'instruction': 'String that can contain characters like -, _ or numbers'}]}

关于python - 将 Erlang 数据解析为 Python 字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59544800/

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