从json中提取推文

时间:2017-08-02 18:35:26

标签: python 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

请告诉我如何提取&#34;文本&#34;此JSON文件中的字段。我尝试使用状态[0] [&#39;文字&#39;]但它出错了:

TypeError:list indices必须是整数或切片,而不是str

请帮帮我。

1 个答案:

答案 0 :(得分:0)

使用

状态[0]的.text

将为您提供值