Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/364.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将包含转义字符的字符串转换为dict_Python_String_Dictionary_Escaping - Fatal编程技术网

Python 将包含转义字符的字符串转换为dict

Python 将包含转义字符的字符串转换为dict,python,string,dictionary,escaping,Python,String,Dictionary,Escaping,我需要将表示dict的python字符串转换为python dict。该字符串可能包含任何有效的dict表示,包括windows样式的路径(带反斜杠),例如 我需要一个通用的str-to-dict转换函数,所以这只是一个源字符串的示例,它不起作用。源字符串可能来自外部源。最好使用与python 2/3兼容的解决方案 我已经试过给出的答案: 加载不起作用(即使我将字符串重新格式化为json语法):引发异常 ast.literal_eval不起作用:在本例中,它在结果中放置一个制表符 eval:与a

我需要将表示dict的python字符串转换为python dict。该字符串可能包含任何有效的dict表示,包括windows样式的路径(带反斜杠),例如

我需要一个通用的str-to-dict转换函数,所以这只是一个源字符串的示例,它不起作用。源字符串可能来自外部源。最好使用与python 2/3兼容的解决方案

我已经试过给出的答案:

加载不起作用(即使我将字符串重新格式化为json语法):引发异常

ast.literal_eval不起作用:在本例中,它在结果中放置一个制表符


eval:与ast.literal的结果相同\u eval

我会在字符串上添加一个hack,将'c:'替换为原始字符串literal 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
{"baselocaldir":"c:\\tmp\\SrcTmp\\RepManager"}
dict key "baselocaldir" =  c:\tmp\SrcTmp\RepManager
original string =  {"baselocaldir":"c:  mp\SrcTmp\RepManager"}
Raw string =  '{"baselocaldir":"c:\tmp\\SrcTmp\\RepManager"}'
rep string =  '{"baselocaldir":"c:\tmp\\SrcTmp\\RepManager"}'
Edit2:显然,仅使用repr()是不够的,这就是为什么我编辑了我的答案,使用regex并将所有的
\
替换为
\
,下面是代码:

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"])
前面的答案,这是不够的 编辑: 将字符串转换为原始字符串的简单方法是使用
repr()
“%r”

这是一个一步解决方案,可追溯到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)
输出:

{"baselocaldir":"c:\\tmp\\SrcTmp\\RepManager"}
dict key "baselocaldir" =  c:\tmp\SrcTmp\RepManager
{"baselocaldir":"c:\\tmp\\SrcTmp\\RepManager"}
dict key "baselocaldir" =  c:\tmp\SrcTmp\RepManager
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)



这个字符串是如何派生的?似乎无论是什么原因导致它没有使用正确的约定/方法,字符串:\t中都有一个制表符(来自“c:\tmp…”)。没有制表符“c:\tmp…”将有一个制表符“c:\\tmp\\…”只是一个反斜杠。两个答案都不起作用,因为输入字符串是mystring=u'{“baselocaldir”:“c:\\tmp\\SrcTmp\\RepManager”},而不是mystring=u'{”baselocaldir“:“c:\tmp\SrcTmp\RepManager”}@carstenthielape,使用新字符串更简单,我们可以跳过使用正则表达式,检查顶部我编辑的答案,它在python 3.6上工作您是对的,它在python 3.x上工作,但在python 2.x上失败。xd不工作,因为输入字符串是mystring=u'{“baselocaldir”:“c:\\tmp\\SrcTmp\\RepManager”}'而不是mystring=u'{“baselocaldir”:“c:\tmp\SrcTmp\RepManager”}”-和:需要将所有其他特殊字符替换为\n\a…我编辑了我的答案。基本上,您可以将值字符串转换为原始文字,这样它将忽略\t\n\a和其他特殊字符。编辑:不是解决方案,这将损坏(转义)字符串的unicode部分