【问题标题】:Convert a string to a dictionary in Python?在 Python 中将字符串转换为字典?
【发布时间】:2011-06-10 05:34:27
【问题描述】:

我正在从 twitter 中提取数据,该数据采用 python 字典的结构,但数据保存在字符串变量中。

如何在 Python 中将此字符串变量转换为字典?

感谢您的帮助!

编辑:Here 是数据示例。

【问题讨论】:

    标签: python json twitter


    【解决方案1】:

    正如 unutbu 所说,您应该使用 json 模块。 使用您的示例数据,我可以这样做:

    import json
    import codecs
    tweet = codecs.open('example.txt', encoding='utf8').read()
    data = json.loads(tweet)
    print keys(data)
    

    有了这个结果:

    [u'favorited', u'in_reply_to_user_id', u'retweeted_status', u'contributors', u'truncated', u'entities', u'text', u'created_at', u'retweeted', u'in_reply_to_status_id', u'coordinates', u'id', u'source', u'in_reply_to_status_id_str', u'in_reply_to_screen_name', u'id_str', u'place', u'retweet_count', u'geo', u'in_reply_to_user_id_str', u'user']
    

    没有错误消息。也许您可以在相关代码中包含一些错误案例的示例数据?

    【讨论】:

      【解决方案2】:

      您可能正在寻找json 模块。

      例如,

      In [165]: json.loads('{"a": 0, "c": 0, "b": 0}')
      Out[165]: {u'a': 0, u'b': 0, u'c': 0}
      

      【讨论】:

      • 谢谢!你知道为什么它会给我:ValueError:未终止的字符串开始于:第1行第1403列(char 1403)?这发生在多条推文上——我只是不知道究竟是什么原因造成的。
      • @Andrew:发文从1402开始。
      • 能否请您解释一下如何轻松做到这一点?
      • @Andrew:看起来有未转义的引号弄乱了 json。你能告诉我们你用来下载这个字符串的代码吗?
      • 非常感谢您的帮助,但我已经找到了问题所在。我只需要使用正则表达式来查找奇怪放置的引号,然后用空格替换它们。
      猜你喜欢
      • 2012-06-14
      • 1970-01-01
      • 2018-05-19
      • 2013-03-13
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      • 2020-11-17
      相关资源
      最近更新 更多