2013-05-26 42 views
3

我是Python和JSON的新手。我安裝了twython以「發言」Twitter API。我在Mac上使用Python 2.7。JSON或SimpleJSON和Python與Twython

我想通過API獲得我的提及。該計劃應確定提到我的Twitter用戶。

我嘗試:

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

的用戶曾經提到,打印男人這樣表示了很多東西:

[{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}] 

某處在這個東西,我看到的一切我都喜歡的東西來從響應中提取。

如何提取screen_name

我很困惑json.dumpsjson.loads - 我應該與jsonsimplejson

+0

我已經得到了解決 - 只有一個: 用於提男性: \t畝=提[「用戶」] \t \t tweetid =提[ '身份證'] \t用戶N =畝[ 'SCREEN_NAME'] \t打印tweetid \t打印用戶N – hildwin

回答

2

你不需要使用json(或simplejson,這是完全相同的庫;它與Python捆綁時被重新命名); Twython庫已經爲您解碼了來自JSON的所有內容。

您從API獲取了一個列表,每個條目都是dict;每個這樣的字典是一個Tweet。您可以看到Twitter API documentation中包含的內容。循環播放列表;有些項目是字典或者列出自己:

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

找出完整結構,使用pprint.pprint()打印結構性版本:

import pprint 

pprint.pprint(men) 

這將使它更容易爲你找出你能做的事遍歷等

+0

謝謝,但我得到一個錯誤: KeyError異常: 'SCREEN_NAME' 也許我應該指出, SCREEN_NAME是實體 看起來這的一部分: u'entities ':{u'symbols':[], \t u'user_mentions ':[{u'id':1457484992, \t u'indices' :[0,8], \t u'id_str':u'1457484992', \t u'screen_name':u'CyclopT',... – hildwin

+0

@hildwin:我在之前的編輯中遇到錯誤;你能告訴我你用了什麼嗎?使用'pprint'技巧來找出什麼是列表和什麼是字典。 –

+0

第二個循環將不起作用。其結構是: 'u'user ':{u'screen_name':u'NAME」 (更多的東西) }' – hildwin