Вопрос

I'm a newbie to Python and JSON as well. I installed twython to "speak" to the Twitter API. I use Python 2.7 on a mac.

I would like to get my mentions through the API. The program should identify the Twitter user who mentioned me.

I try:

t = Twython(...)
men = t.get_mentions_timeline()

The user is mentioned once, print men shows a lot of stuff like this:

[{u'contributors': None, u'truncated': False, u'text': .... u'Sun May 26 09:18:55 +0000 2013', u'in_reply_to_status_id_str': None, u'place': None}]

Somewhere in this stuff I see all the things I would like to extract from the response.

How can I extract the screen_name?

I'm quite confused with json.dumps or json.loads - shall I work with json or simplejson?

Это было полезно?

Решение

You don't need to use json (or simplejson, which is the exact same library; it was renamed when bundled with Python); the Twython library already decoded everything from JSON for you.

You got a list from the API, each entry is a dict; each such dictionary is a Tweet. You can see what is contained in the Twitter API documentation. Loop over that list; some items are dictionaries or lists themselves:

for mention in men:
    print mention['user']['screen_name']
    if mention['contributors']:
        print [con['screen_name'] for con in mention['contributors']]

To figure out the full structure, use pprint.pprint() to print a structured version:

import pprint

pprint.pprint(men)

which will make it easier for you to figure out what you can loop over, etc.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top