'Tweepy - 'tweet.text' not retrieving text
I am brand new to Python, APIs, and coding in general.
I am working on a Twitter sentiment analyzing bot, but I cannot figure out why it isn't returning the text field. Everytime I run my script, PyCharm gives me AttributeError: 'list' object has no attribute 'text'. Could anyone please help?
I have defined my tokens and API keys above these lines:
def authentication(cons_key, cons_secret, access_token, access_secret):
auth = tw.OAuthHandler(cons_key, cons_secret)
auth.set_access_token(acces_token, access_secret)
api = tw.API(auth, wait_on_rate_limit=True)
#Sentiment Analysis Block
query = input('Enter keyword/hashtag to search: ')
#numtweets = int(input('How many tweets you would like analyzed: ')) #update with paginator
#Defining percentage, for use on percent of sentiment
#def percentage(part, whole):
# return 100 *float(part)/float(whole)
tweets = client.search_recent_tweets(query=query, max_results=100)
#positive = 0
#neutral = 0
#negative = 0
#polarity = 0
#tweet_list = []
#positive_list = []
#neutral_list = []
#negative_list = []
for tweet in tweets:
print(tweet.text)
#tweet_list.append(str(tweet.text))
#analysis = TextBlob(tweet.text)
#score = SentimentIntensityAnalyzer().polarity_scores(tweet.text)
#pos = score['pos']
#neu = score['neu']
#neg = score['neg']
#comp = score['compound']
#polarity += analysis.sentiment.polarity
As soon as the script gets to print(tweet.text), it gives me the error. Any feedback?
Solution 1:[1]
tweets is a tweepy.Response (named tuple) object. You're iterating over its fields rather than Tweet objects, and its first data field is a list of Tweet objects. Hence the error that the list doesn't have a text attribute. You probably want to iterate over the data field instead.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Harmon758 |
