Hem*_*hah 12 python dictionary
我有如下字符串:
s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'
Run Code Online (Sandbox Code Playgroud)
我想转换成字典如下:
key | value -----|-------- key1 | 1234 key2 | string with space key3 | SrtingWithoutSpace
我如何在Python中执行此操作?
Joc*_*zel 26
该shlex类可以很容易地编写简单的语法类似的Unix外壳的词法分析器.这对于编写小语言(例如,在Python应用程序的运行控制文件中)或解析引用的字符串通常很有用.
import shlex
s = 'key1=1234 key2="string with space" key3="SrtingWithoutSpace"'
print dict(token.split('=') for token in shlex.split(s))
Run Code Online (Sandbox Code Playgroud)
Mar*_*ers 17
试试这个:
>>> import re
>>> dict(re.findall(r'(\S+)=(".*?"|\S+)', s))
{'key3': '"SrtingWithoutSpace"', 'key2': '"string with space"', 'key1': '1234'}
Run Code Online (Sandbox Code Playgroud)
如果您还想删除引号:
>>> {k:v.strip('"') for k,v in re.findall(r'(\S+)=(".*?"|\S+)', s)}
Run Code Online (Sandbox Code Playgroud)