[英]Convert String to Dict in Python
我正在嘗試將以下類型的字符串轉換為 Python 中的字典。
'F1=Value1,F2=Value2,F3=[[F4=Value4,F5=Value5]],F6=Value6'
我想讓字典像:
{
'F1': 'Value1',
'F2': 'Value2',
'F3': '[[F4=Value4,F5=Value5]]',
'F6': 'Value6'
}
如果您將繼續使用相同的字符串格式,您可以使用復雜的正則表達式來覆蓋各種模式。
以下是我預期的一些模式的正則表達式。 如果這能解決您的問題,請告訴我。 如果沒有,請提供有關我的解決方案失敗的詳細信息:
編輯解釋
(?=F\\d+=\\[).*?(\\]){2,}(?=|,)
(?=F\\d+=\\[)
匹配字符串以F開頭,有一個或多個數字,后面有=[
.*?(\\]){2,}
盡可能少地匹配字符串,並且在末尾有 2 個或更多]
(?=|,)
字符串結尾,
或者什么都沒有F\\d.[^,]+
F6=Value6
這樣的字符串。 因為第一組優先於第二組,所以第二組只能匹配剩余的字符串。代碼
string = "F1=Value1,F2=Value2,F3=[[F4=Value4,F5=Value5]],F6=Value6,F7=[[[BC],[AC]]]"
import re
resultset = [ele[0] if ele[0] else ele[-1] for ele in re.findall(r"((?=F\d+=\[).*?(\]){2,}(?=|,))|(F\d.[^,]+)",string)]
print({x[:x.find("=")]:x[x.find("=")+1:] for x in resultset})
輸出
{'F6': 'Value6', 'F2': 'Value2', 'F3': '[[F4=Value4,F5=Value5]]', 'F1': 'Value1', 'F7': '[[[BC],[AC]]]'}
編輯:因為當字符串為F1=Value1,F2=Value2,F8=[iD=10,ig=12S],F3=[[F4=Value4,F5=Value5]],F6=Value6,F9=[iD=10,ig=12S],F7=[[[BC],[AC]]]
前正則表達式不起作用F1=Value1,F2=Value2,F8=[iD=10,ig=12S],F3=[[F4=Value4,F5=Value5]],F6=Value6,F9=[iD=10,ig=12S],F7=[[[BC],[AC]]]
我將正則表達式更改為((?=F\\d+=\\[).*?(\\])+(?= |,F))|(F\\d.[^,]+)
。 我們需要一個技巧。 在 string 后添加一個空格。
string = "F1=Value1,F2=Value2,F8=[iD=10,ig=12S],F3=[[F4=Value4,F5=Value5]],F6=Value6,F9=[iD=10,ig=12S],F7=[[[BC],[AC]]]"
import re
resultset = [ele[0] if ele[0] else ele[-1] for ele in re.findall(r"((?=F\d+=\[).*?(\])+(?= |,F))|(F\d.[^,]+)",string+" ")]
print({x[:x.find("=")]:x[x.find("=")+1:] for x in resultset})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.