简体   繁体   English

Python python中如何将带特殊字符的字符串转成dict

[英]Python How to convert string with special characters into a dict in python

I'm trying to covert a string into a valid dict.我正在尝试将字符串转换为有效的字典。

For example the string:例如字符串:

'{"value1":"\^stack\.\*/overflo\\w\$arr=1", "value2":"path c:\nord\tem\orme\test.exe"}'

I want to get a dict我想听写

{"value1":"\^stack\.\*/overflo\\w\$arr=1", 
 "value2":"path c:\nord\tem\norme\test.exe"} 

How to convert this string into a dict without loosing spicial characters and without using backslash escape.如何在不丢失特殊字符且不使用反斜杠转义的情况下将此字符串转换为字典。

a_string = '{"value1":"\^stack\.\*/overflo\\w\$arr=1", "value2":"path c:\nord\tem\orme\test.exe"}'
a_dict = json.loads(a_string) # desired result a_dict = {"value1":"^stack.*/overflo\w$arr=1", "value2":"path c:\nord\tem\orme\test.exe"}

first of all, regular expression ("regex" for short) is not contextual grammar, thus it cannot differentiate whether an asterix ("*") inside pair of braces needs to be preserved, while others must be removed.首先,正则表达式(简称“regex”)不是上下文文法,因此无法区分一对大括号内的星号(“*”)是否需要保留,而其他必须去掉。 Regex treats every character equally.正则表达式平等对待每个字符。

If the extra characters (here: asterixes) appear only at the beginning and at the end of json-like string, and you know that there are two of them on both ends, you can use slices to achieve your goal:如果多余的字符(这里是星号)只出现在json-like字符串的开头和结尾,并且你知道两端有两个,你可以使用切片来实现你的目标:

a_string = '**{"key1":"value1","key2":"value2"}**'
json_string = a_string[2:len(a_string)-2] # shortly: a_string[2:-2]
d = json.loads(json_string)
print(d)
#>>> {"key1":"value1","key2":"value2"}

You could use a generator, something like this:您可以使用生成器,如下所示:

original_String = "John - 10 , Rick - 20, Sam - 30" 

result = dict((a.strip(), int(b.strip()))  
                     for a, b in (element.split('-')  
                                  for element in original_String.split(', ')))  

The original string is John - 10, Rick - 20, Sam - 30原始字符串为John - 10, Rick - 20, Sam - 30

The resultant dictionary is: {'John': 10, 'Rick': 20, 'Sam': 30}结果字典是: {'John': 10, 'Rick': 20, 'Sam': 30}

if you can remove ** of the first and end of the string you can use this standard python package to transform any string that is like a dictionary into a valid dictionary.如果可以删除字符串开头和结尾的** ,则可以使用此标准 python package 将任何类似于字典的字符串转换为有效字典。

>>> import ast
>>> a_string = r'{"value1":"\^stack\.\*/overflo\\w\$arr=1", "value2":"path c:\nord\tem\orme\test.exe"}'
>>> a_dict = ast.literal_eval(a_string)
>>> a_dict
{'value1': '\\^stack\\.\\*/overflo\\w\\$arr=1', 'value2': 'path c:\nord\tem\\orme\test.exe'}

python document: https://docs.python.org/3/library/ast.html#ast.literal_eval python 文档: https://docs.python.org/3/library/ast.html#ast.literal_eval

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM