2017-08-02 31 views
2

提取鳴叫我用下面的代碼來獲得一個鳴叫:從JSON

import twitter 
import tweepy 
import json 
CONSUMER_KEY = "" 
CONSUMER_SECRET="" 
OAUTH_TOKEN="" 
OAUTH_TOKEN_SECRET="" 

twitter_api = twitter.Api(CONSUMER_KEY, 
        CONSUMER_SECRET, 
        OAUTH_TOKEN, 
       OAUTH_TOKEN_SECRET) 


auth = tweepy.auth.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET) 
auth.set_access_token(OAUTH_TOKEN, OAUTH_TOKEN_SECRET) 
twitter_api1 = tweepy.API(auth, parser=tweepy.parsers.JSONParser()) 

search_results = twitter_api1.search(q="Movies", count=1) 
statuses = search_results['statuses'] 
print(json.dumps(statuses[0], indent =1)). 

此代碼提供了以下JSON文件:

{ 
"created_at": "Wed Aug 02 18:21:35 +0000 2017", 
"id": 892812639314817033, 
"id_str": "892812639314817033", 
"text": "\"The Best TV Shows and Movies New to Netflix, Amazon and More in August\" by MONICA CASTILLO via NYT ", 
"truncated": false, 
"entities": { 
"hashtags": [], 
"symbols": [], 
    "user_mentions": [], 
    "urls": [ 
    { 
    "url": "", 
    "expanded_url": "", 
    "display_url": "", 
    "indices": [ 
    100, 
    123 
    ] 
    } 
    ] 
}, 
"metadata": { 
    "iso_language_code": "en", 
    "result_type": "recent" 
}, 
    "source": "<a href=\"https://ifttt.com\" rel=\"nofollow\">IFTTT</a>", 
    "in_reply_to_status_id": null, 
"in_reply_to_status_id_str": null, 
"in_reply_to_user_id": null, 
"in_reply_to_user_id_str": null, 
"in_reply_to_screen_name": null, 
"user": { 
    "id": 39630578, 
    "id_str": "39630578", 
    "name": "TV Mogul", 
    "screen_name": "TheTVStation", 
    "location": "Behind the Remote Control", 
    "description": "So many shows..so many networks....when is your favorite 
time to watch? Who is your favorite news or personality at your station..down the street from The Rink", 
    "url": null, 
    "entities": { 
    "description": { 
    "urls": [] 
    } 
} 
. 
. 
. AND SO On 

請告訴我怎樣可以提取「文本「來自這個JSON文件的字段。我試着用狀態[0] [「文本」],但它給出了一個錯誤說:

類型錯誤:列表索引必須是整數或片,而不是str的

請幫助我。

+1

你肯定是對'狀態的錯誤信息[0] [ '文本']'?它看起來更像是你會爲'statuses ['text']'獲得的錯誤信息。請顯示* full * traceback,以便我們可以看到Python指出的是什麼。 –

回答

0

使用

狀態[0] .text區段

,會給你的價值

+0

原來,在使用該語句之前,需要將JSON轉換爲Python字典。不過謝謝,它幫助了很多! –