3

我想将 Tweepyapi.trends_location(woeid)调用的结果转换为 dict(或 dicts 的 dict),这样我就可以使用这些值(真的,我想最终得到一个 'name' 值的 dict)。Tweepy 文档说结果是“一个 JSON 对象”(见这里),但是当我检索它时,type(retrieved)计算结果为list. 果然,retrieved有一个len1的,retrieved[0]给我一个单品:
[{'trends': [{'url': 'http://search.twitter.com/search?q=%23questionsidontlike', 'query': '%23questionsidontlike', 'events': None, 'promoted_content': None, 'name': '#questionsidontlike'}, ], (more of the same), 'created_at': '2011-01-31T22:39:16Z', 'as_of': '2011-01-31T22:47:47Z', 'locations': [{'woeid': 23424977, 'name': 'United States'}]}]

我可以调用json.dumps,这将提供格式良好的表示,但这对我来说没有多大用处,并json.loads给了我:__init__() got an unexpected keyword argument 'sort_keys'

我应该如何进行?

完整代码链接:https ://gist.github.com/805129

4

4 回答 4

3

好的,应该这样做!它甚至经过测试(感谢发布附加信息)。

>>> names = [trend["name"] for trend in retrieved[0]["trends"]]
>>> names
['#wishuwould', '#questionsidontlike', '#februarywish', 'Purp & Patron', 'Egyptians', 'Kool Herc', 'American Pie', 'Judge Vinson', 'Eureka Nutt', 'Eddie House']

我认为大部分混淆来自将输出称为 JSON 对象的文档,这与需要使用json模块转换的 JSON 字符串不同。

这是如何工作的:retrieved是一个包含单个项目的列表,它是包含trendsretrieved[0]["trends"]的字典,趋势字典列表也是如此,其中每个趋势字典都包含name您感兴趣的键。

于 2011-01-31T23:39:58.780 回答
2

像这样的东西对你有用吗?

def searchKeys(struct, keys, result = None, recursive = True):
        if result is None:
                result = []

        if isinstance(struct, dict):
                for k in keys:
                        if struct.has_key(k):
                                result.append(struct[k])

                if recursive:
                        for i in struct.values():
                                searchKeys(struct = i, keys = keys, result = result, recursive = recursive)
        elif isinstance(struct, list):
                if recursive:
                        for i in struct:
                                searchKeys(struct = i, keys = keys, result = result, recursive = recursive)

        return result

使用示例:

>>> searchKeys(struct = a, keys = ['name'])
['United States', '#questionsidontlike']

它递归地沿着dict/list层次结构搜索一组dict键并将相应的值存储到 a list

于 2011-01-31T23:39:41.573 回答
1

要将 Tweepy 'Status' 对象转换为 Python 字典 (JSON),请访问对象上的私有成员“_json”。

tweets = tweepy_api.user_timeline(screen_name='seanharr11')
json_tweets = map(lambda t: t._json, tweets)
于 2017-02-11T15:24:53.310 回答
0
>>> import simplejson
>>> a = {"response":[{"message":"ok"},{"message":"fail"}]}
>>> json = simplejson.dumps(a)
>>> simplejson.loads(json)
{'response': [{'message': 'ok'}, {'message': 'fail'}]}

http://docs.python.org/library/json.html

于 2011-01-31T23:53:45.563 回答