【发布时间】:2011-06-10 05:34:27
【问题描述】:
我正在从 twitter 中提取数据,该数据采用 python 字典的结构,但数据保存在字符串变量中。
如何在 Python 中将此字符串变量转换为字典?
感谢您的帮助!
编辑:Here 是数据示例。
【问题讨论】:
我正在从 twitter 中提取数据,该数据采用 python 字典的结构,但数据保存在字符串变量中。
如何在 Python 中将此字符串变量转换为字典?
感谢您的帮助!
编辑:Here 是数据示例。
【问题讨论】:
正如 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']
没有错误消息。也许您可以在相关代码中包含一些错误案例的示例数据?
【讨论】:
您可能正在寻找json 模块。
例如,
In [165]: json.loads('{"a": 0, "c": 0, "b": 0}')
Out[165]: {u'a': 0, u'b': 0, u'c': 0}
【讨论】: