簡體   English   中英

將包含轉義字符的字符串轉換為字典

[英]Convert string which contains escape characters to a dict

我需要將表示 dict 的 python 字符串轉換為 python dict。 該字符串可能包含任何有效的 dict 表示,包括 Windows 樣式路徑(帶反斜杠),例如

mystring = u'{"baselocaldir":"c:\\tmp\\SrcTmp\\RepManager"}'

我需要一個通用的 str 來 dict 轉換函數,所以這只是一個源字符串的例子,它不起作用。 源字符串可能來自外部源。 首選 python 2/3 兼容解決方案。

我已經嘗試過給出的答案:

json.loads 不起作用(即使我將字符串重新格式化為 json 語法):引發異常

ast.literal_eval 不起作用:在這個例子中它在結果中放置了一個制表符

eval:與 ast.literal_eval 結果相同

我會對字符串進行修改以將 'c:' 替換為原始字符串文字 r'c:'

mystring = u'{"baselocaldir": "c:\\tmp\\SrcTmp\\RepManager"}'.replace('"c:', 'r"c:') 
_dict = eval(mystring)
_dict

結果:

{'baselocaldir': 'c:\\tmp\\SrcTmp\\RepManager'}

Edit3:op將示例字符串更改為雙反斜杠后,更容易,無需使用正則表達式:

mystring = u'{"baselocaldir":"c:\\tmp\\SrcTmp\\RepManager"}'
test = repr(mystring)[1:-1] 
print(test)

# convert to dictionary
my_dict = json.loads(test)
print('dict key "baselocaldir" = ', my_dict["baselocaldir"])

輸出:

{"baselocaldir":"c:\\tmp\\SrcTmp\\RepManager"}
dict key "baselocaldir" =  c:\tmp\SrcTmp\RepManager

Edit2:顯然單獨使用 repr() 是不夠的,這就是為什么我編輯了我的答案以使用正則表達式並將所有\\替換為\\\\ ,這是代碼:

import re, json
mystring = u'{"baselocaldir":"c:\tmp\SrcTmp\RepManager"}'

test = re.sub(r'(?<=[^\\])\\(?=[^\\])', r'\\\\', repr(mystring)[1:-1])
print(test)

# convert to dictionary
my_dict = json.loads(test)
print('dict key "baselocaldir" = ', my_dict["baselocaldir"])

輸出:

{"baselocaldir":"c:\\tmp\\SrcTmp\\RepManager"}
dict key "baselocaldir" =  c:\tmp\SrcTmp\RepManager

以前的答案,這還不夠 編輯:將字符串轉換為原始字符串的簡單方法是使用repr()"%r"

這是一個一步解決方案,歸功於Nishanth Amuluru 和 Jed Alexander 9 年前:

mystring = u'{"baselocaldir":"c:\tmp\SrcTmp\RepManager"}'

raw_str = "%r"%mystring
rep_str= repr(mystring)

print('original string = ', mystring)
print('Raw string = ', raw_str)
print('rep string = ', rep_str)

輸出:

original string =  {"baselocaldir":"c:  mp\SrcTmp\RepManager"}
Raw string =  '{"baselocaldir":"c:\tmp\\SrcTmp\\RepManager"}'
rep string =  '{"baselocaldir":"c:\tmp\\SrcTmp\\RepManager"}'

我的(也許不是最優雅的)解決方案:

但它適用於 python2 、 python3 和 unicode 字符串中的 unicode 字符:


text_type = None
if PY2:
    string_types = basestring
    text_type = unicode
else:
    string_types = text_type = str

def DictUnescaceBackslash(oDict):
    for key, value in iteritems(oDict):
        if isinstance(value, dict):
            DictUnescaceBackslash(value)
        elif isinstance(value, string_types):
            oDict[key]=oDict[key].replace("***BaCkSlAsH***","\\")
        elif isinstance(value, list):
           for elem in value:
                DictUnescaceBackslash(elem)

mystring = u'{"baselocaldir":"c:\\tmp\\SrcTmp\\RepManager"}'
uString2 = mystring.replace("\\","***BaCkSlAsH***")
dDict    = ast.literal_eval(uString2)
DictUnescaceBackslash(dDict)


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM