我用于專案的 API 端點回傳以下形式的純文本回應:
[RESPONSE]
code = 200
description = Command completed successfully
queuetime = 0
runtime = 0.071
property[abuse policy][0] = The policies are published at the REGISTRY_OPERATOR website at:
property[abuse policy][1] = =>https://registry.in/Policies
property[abuse policy][2] =
property[abuse policy][3] = IN Policy Framework: https://registry.in/system/files/inpolicy_0.pdf
property[abuse policy][4] = IN Domain Anti-Abuse policy: https://registry.in/Policies/IN_Anti_Abuse_Policy
property[abuse policy url][0] = https://registry.in/Policies/IN_Anti_Abuse_Policy
property[active][0] = 0
我正在嘗試使用 Python 將其決議為字典。目前,我有以下代碼:
import re
def text_to_dict(text):
js = {}
for s in text.splitlines():
x = s.split("=", maxsplit=1)
if len(x) > 1:
keys = [k for i in re.split("\]|\[", x[0]) if (k := i.strip())]
for i, k in enumerate(keys):
pd = js
for j,pk in enumerate(keys[:i]):
if keys[j 1:j 2] and not (keys[j 1:j 2][0]).isnumeric():
pd = pd[pk]
if k not in pd:
if k.isnumeric():
pd[keys[i-1]].append((x[1]).strip())
else:
pd[k] = (x[1]).strip() if i == len(keys)-1 else [] if keys[i 1:i 2] and (keys[i 1:i 2][0]).isnumeric() else {}
return js
這段代碼可以處理上面的例子,它回傳:
{
"code": "200",
"description": "Command completed successfully",
"runtime": "0.081",
"queuetime": "0",
"property": {
"abuse policy": [
"The policies are published at the REGISTRY_OPERATOR website at:",
"=>https://registry.in/Policies",
"",
"IN Policy Framework: https://registry.in/system/files/inpolicy_0.pdf",
"IN Domain Anti-Abuse policy: https://registry.in/Policies/IN_Anti_Abuse_Policy"
],
"abuse policy url": [
"https://registry.in/Policies/IN_Anti_Abuse_Policy"
],
"active": [
"0"
]
}
}
但是,如果我將其附加到上面的示例中,它將無法處理以下內容:
...
property[active][1][test] = TEST
要么
...
property[active][1][0] = TEST
應該回傳
{
...
"active": [
"0",
{"test": "TEST"}
]
}
和
{
...
"active": [
"0",
["TEST"]
]
}
分別。
我覺得有一種更簡單的方法來解釋所有可能性,而無需撰寫一堆嵌套的 if,但我不確定是什么。
uj5u.com熱心網友回復:
您的輸入資料實際上是 INI 檔案格式。Python具有configparser方便的模塊。
當我們假設鍵的每個部分'property[foo][0][test]'實際上都是一個 dict 鍵(沒有嵌套串列)時,我們會將其決議為以下結構:
{'property': {'foo': {'0': {'test': 'value'}}}}
這可以通過不斷創建嵌套字典的回圈來完成:
from configparser import ConfigParser
def parse(text):
config = ConfigParser()
config.read_string(text)
root = {}
for key in config['RESPONSE'].keys():
curr = root
for key_part in key.replace(']', '').split('['):
if key_part not in curr:
curr[key_part] = {}
prev = curr
curr = curr[key_part]
prev[key_part] = config['RESPONSE'][key]
return root
用法
from pprint import pprint
text = """
[RESPONSE]
code = 200
description = Command completed successfully
queuetime = 0
runtime = 0.071
property[abuse policy][0] = The policies are published at the REGISTRY_OPERATOR website at:
property[abuse policy][1] = =>https://registry.in/Policies
property[abuse policy][2] =
property[abuse policy][3] = IN Policy Framework: https://registry.in/system/files/inpolicy_0.pdf
property[abuse policy][4] = IN Domain Anti-Abuse policy: https://registry.in/Policies/IN_Anti_Abuse_Policy
property[abuse policy url][0] = https://registry.in/Policies/IN_Anti_Abuse_Policy
property[active][0] = 0
property[foo][0][test] = a
property[foo][1][test] = b
property[bar][0][0] = A
property[bar][1][1] = B
"""
pprint(parse(text))
結果
{'code': '200',
'description': 'Command completed successfully',
'property': {'abuse policy': {'0': 'The policies are published at the '
'REGISTRY_OPERATOR website at:',
'1': '=>https://registry.in/Policies',
'2': '',
'3': 'IN Policy Framework: '
'https://registry.in/system/files/inpolicy_0.pdf',
'4': 'IN Domain Anti-Abuse policy: '
'https://registry.in/Policies/IN_Anti_Abuse_Policy'},
'abuse policy url': {'0': 'https://registry.in/Policies/IN_Anti_Abuse_Policy'},
'active': {'0': '0'},
'bar': {'0': {'0': 'A'}, '1': {'1': 'B'}},
'foo': {'0': {'test': 'a'}, '1': {'test': 'b'}}},
'queuetime': '0',
'runtime': '0.071'}
您可以檢查是否key_part為數字,并將其轉換為int結果結構的行為更像它包含串列,即
{'property': {'foo': {0: {'test': 'value'}}}}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/446035.html
上一篇:如何從Telegramm訊息中獲取標題(Pyrogram)
下一篇:Python部分日期決議器函式
