我是 regex 模塊的新手,并且學習了一個簡單的案例來從一個簡單的字典中提取鍵和值。
字典不能包含嵌套字典和任何串列,但可能有簡單的元組
MWE
import re
# note: the dictionary are simple and does NOT contains list, nested dicts, just these two example suffices for the regex matching.
d = "{'a':10,'b':True,'c':(5,'a')}" # ['a', 10, 'b', True, 'c', (5,'a') ]
d = "{'c':(5,'a'), 'd': 'TX'}" # ['c', (5,'a'), 'd', 'TX']
regexp = r"(.*):(.*)" # I am not sure how to repeat this pattern separated by ,
out = re.match(regexp,d).groups()
out
uj5u.com熱心網友回復:
您不應該在這項作業中使用正則運算式。當輸入字串是有效的 Python 語法時,您可以使用ast.literal_eval.
像這樣:
import ast
# ...
out = ast.literal_eval(d)
現在你在 Python 中有一個字典物件。例如,您可以在 (dict_items) 串列中獲取鍵/值對:
print(out.items())
正則運算式
正則運算式不是正確的工具。總會有一些邊界情況被錯誤決議的情況。但是要獲得重復匹配,您可以更好地使用findall. 這是一個簡單的正則運算式示例:
regexp = r"([^{\s][^:]*):([^:}]*)(?:[,}])"
out = re.findall(regexp, d)
這將給出一個配對串列。
uj5u.com熱心網友回復:
由于嵌套在元組中的“,”,正則運算式很難使用(可能是不可能的,但我不夠熟練,無法自信地說)。只是為了它,我撰寫了(無正則運算式)代碼來決議您的字串以查找分隔符,忽略括號內的部分:
d = "{'c':(5,'a',1), 'd': 'TX', 1:(1,2,3)}"
d=d.replace("{","").replace("}","")
indices = []
inside = False
for i,l in enumerate(d):
if inside:
if l == ")":
inside = False
continue
continue
if l == "(":
inside = True
continue
if l in {":",","}:
indices.append(i)
indices.append(len(d))
parts = []
start = 0
for i in indices:
parts.append(d[start:i].strip())
start = i 1
parts
# ["'c'", "(5,'a',1)", "'d'", "'TX'", '1', '(1,2,3)']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532397.html
標籤:Python解析
上一篇:C中的決議器不會將值存盤在陣列中
