问题描述
我是编程新手,正在将 Python 应用到我需要分析特定 Twitter 主题标签的项目中。我已成功显示特定主题标签的推文,但无法将它们保存到 JSON 文件中。
我将不胜感激
在我的代码下面:
#Import necessary libaries to access Twitter
import os
import tweepy as tw
import pandas as pd
import tweepy as OAuthHandler
# Access keys and tokens to Twitter
consumer_key=''
consumer_secret=''
access_token=''
access_token_secret=''
#Access Twitter
auth = tw.OAuthHandler(consumer_key,consumer_secret)
auth.set_access_token(access_token,access_token_secret)
#this to allow us to generate multiple requests and skip the waiting time
api = tw.API(auth,wait_on_rate_limit=True)
#Define the query of our search
#query='#Astrazeneca'
query=input('print selected hashtag starting with #: ')
tweets=tw.Cursor(api.search,q=query,lang='en').items(50)
#for tweet in tweets:
#print(tweet.text)
# make the tweets in a list
all_tweets=[tweet.text for tweet in tweets]
all_tweets[0:5]
# Save tweets to JSON file
import json
for tweet in all_tweets:
with open('tweetsfile._json','w',encoding='utf8') as file:
json.dump(tweet._json,file,sort_keys = True,indent = 4)
我收到的错误:
AttributeError Traceback (most recent call last)
<ipython-input-4-a82813c9d641> in <module>
3 for tweet in all_tweets:
4 with open('tweet.text_json',encoding='utf8') as file:
----> 5 json.dump(tweet._json,indent = 4)
AttributeError: 'str' object has no attribute '_json'
解决方法
当您创建列表 all_tweets
时,您正在调用 tweet.text
,它返回一个 string
。 string
没有属性 _json
,但是您的 tweet
对象(在调用 .text
之前有。
更改它以包含对象 tweet
而不是它应该打开在循环中调用 tweet._json
的能力。
all_tweets=[tweet for tweet in tweets]