我有一串数据。我想把它变成一个 字典
ff = '{wrapper:{one:{now:""},up:"north",down:"south"}}'
请注意,这些密钥不是用'或"。正则表达式可以帮助做到这一点吗?新文本应如下所示。如果熊猫可以做到这一点,我可以 用熊猫。
ff = '{"wrapper":{"one":{"now":""},"up":"north","down":"south"}}'
答案 0 :(得分:4)
使用环视:
(?<={).*?(?=:)
,其中
(?<={) - match { before
.*? - non greedy
(?=:) - match : after
所以在代码中它会是..
import re
import json
str = '{wrapper:{one:{now:""},up:"north",down:"south"}}'
str = re.sub('(?<=[{,])(.*?)(?=:)', r'"\1"', str)
jsonobj = json.loads(str)
print jsonobj
答案 1 :(得分:0)
(loop
for x = (string-upcase (string (read-char)))
while (not (equal " " x))
collecting (intern x))
- 负面展望。
(?!")
输出:
def st_to_dict(st):
import re
return re.sub(r'(\b[^:"]+\b)(?!")',r'"\1"',st)
ff = '{wrapper:{one:{now:""},up:"north",down:"south"}}'
print(st_to_dict(ff))