需要帮助拆分下面的句子并将其转换为字典键值
[score=2 last=19 delay=5 distance=10k 2 events name=Denis John P place=New York]
dict结果应为:
"Event": {
"score": "2",
"last": "19",
"delay": "5",
"distance": "10k 2 events",
"name": "Denis John",
"place": "New York",
}
我无法弄清楚解决方案,尝试了很多但没有分裂的东西=某事,某事物=使用分隔符'='
的东西感谢您的帮助!
答案 0 :(得分:0)
这个解决方案并不完美。它要求每个值以一个空格结束,它会丢弃。我通过在字符串末尾添加一个空格然后剥离每个值来解决这个问题。
import re
s = "score=2 last=19 delay=5 distance=10k 2 events name=Denis John P place=New York"
s = s + ' '
res = re.findall(r"([^\s]+)=([^=]+)\s", s)
res = [(a, b.strip()) for (a,b) in res]
d = {"Events": dict(res)}
答案 1 :(得分:0)
这应该做的工作:
s = '[score=2 last=19 delay=5 distance=10k 2 events name=Denis John P place=New York]'
l = s[1:-1].split('=')
data = {}
while len(l) > 0:
val = l.pop()
if len(l) > 1:
head,key = l.pop().rsplit (maxsplit=1)
l.append (head)
else:
key = l.pop()
data[key] = val
from pprint import pprint
pprint (data)
输出:
{'delay': '5',
'distance': '10k 2 events',
'last': '19',
'name': 'Denis John P',
'place': 'New York',
'score': '2'}