【问题标题】:Save tweets of specific hashtag to JSON file将特定主题标签的推文保存到 JSON 文件
【发布时间】:2021-07-08 04:38:12
【问题描述】:

我是编程新手,我正在将 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','w',encoding='utf8') as file:
----> 5         json.dump(tweet._json, file,sort_keys = True,indent = 4)

AttributeError: 'str' object has no attribute '_json'

【问题讨论】:

    标签: python json twitter tweepy twitterapi-python


    【解决方案1】:

    当您创建列表all_tweets 时,您正在调用tweet.text,它返回一个stringstring 没有属性 _json,但是您的 tweet 对象(在调用 .text 之前。

    将其更改为包含对象 tweet,而不是应该打开在循环中调用 tweet._json 的能力。

    all_tweets=[tweet for tweet in tweets]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-24
      • 2014-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-13
      • 1970-01-01
      相关资源
      最近更新 更多