【问题标题】:Convert string to dictionary where keys are not strings将字符串转换为键不是字符串的字典
【发布时间】:2015-09-16 10:28:37
【问题描述】:

我正在解析一个 html 文件,我最终得到的东西 几乎 看起来像一个 python 字典......除了键不是字符串。因此,我不能使用ast.literal_eval()json.loads()

字符串如下所示:

x = '{name:'Berlin, Germany', daypart:'night', href:'/en/de/berlin/10178/weather-forecast/178087', icon:'http://vortex.accuweather.com/adc2010/images/icons-numbered/33-m.png', bg:'cl', temp:'22',  realfeel:'22',  text:'Clear'}'

我想把它转换成一个 python 字典,其中的键也是字符串。我认为这需要一些好的 ol' 正则表达式,但我不知道该怎么做。

【问题讨论】:

  • 这是有效的 JavaScript,不是 JSON 或 Python,是的。
  • @MartijnPieters 是的,但我正在尝试将其转换为 python dict
  • 试试literal_eval(re.sub(r"(\w+)(?=:')",r"'\1'",x))
  • @PadraicCunningham 是的,为什么不将其发布为答案? :)
  • 这可能更健壮一点,it = iter(re.findall(r"(\w+|[\'\"].*?[\'\"])", x));dict(zip(it,it))

标签: python regex dictionary


【解决方案1】:

也许您可以按照 @Zero Piraeus 来自 similar question 的建议,使用像 PyYAML 这样的 YAML 解析器来读取您的字符串,然后将结果转换为字典。

【讨论】:

    猜你喜欢
    • 2017-02-11
    • 1970-01-01
    • 1970-01-01
    • 2015-12-25
    • 2014-07-06
    • 2021-07-25
    • 1970-01-01
    相关资源
    最近更新 更多