我在从Twitter获取10家公司的数据时遇到了一些问题,我从Twitter为每家公司提取了10万条记录,并对此进行了情绪分析,但在获取记录时它会卡住,然后停止!我正在获取数据执行情绪分析和创建单独的文件然后合并到一个文件,但代码在获取第一家公司本身的数据时陷入困境
import tweepy
from textblob import TextBlob
import pandas as pd
Access_token="`access token here`"
Access_token_secret="`access token secret here`"
Consumer_key="`consumer key here`"
Consumer_secret_key="`consumer secret key here`"
auth=tweepy.OAuthHandler(Consumer_key,Consumer_secret_key)
auth.set_access_token(Access_token,Access_token_secret)
api=tweepy.API(auth)
search_list = ['company names here in a list']
for n in search_list:
positive_tweet = []
negative_tweet = []
neutral_tweet = []
Final_list = []
new_list = []
tweets = tweepy.Cursor(api.search, q=str(n) + '-filter:retweets', lang='en', since='2018-01-01').items(10000)
for tweet in tweets:
print(tweet.text)
analysis = TextBlob(tweet.text)
if (analysis.sentiment.polarity) > 0:
positive_tweet.append(analysis.sentiment.polarity)
elif analysis.sentiment.polarity < 0:
negative_tweet.append(analysis.sentiment.polarity)
elif analysis.sentiment.polarity == 0:
neutral_tweet.append(analysis.sentiment.polarity)
else:
print('Emotionless & No Opinion regarding tweet')
total = len(positive_tweet) + len(negative_tweet) + len(neutral_tweet)
percentage_of_postive_review = float(len(positive_tweet) / (total) * 100)
new_list.append(n)
new_list.append(percentage_of_postive_review)
# print(new_list)
if new_list != []:
label = ['Company Name', 'Review']
i = 0
j = 2
while i < j and j <= len(new_list):
Final_list.append(new_list[i:j])
i = i + 2
j = j + 2
df = pd.DataFrame.from_records(Final_list, columns=label)
# print(df)
df.to_csv('D:/Review_Rating/Company Review' + str(n) + '.csv', index=False)
您的代码生成此错误消息:
tweepy.error.TweepError: Twitter error response: status code = 429
此错误消息与“Too Many Requests”有关。
当您的费率限制用尽时,会抛出此错误。有关速率限制的详细信息,请参阅以下Twitter参考
更改此行代码:
api=tweepy.API(auth)
至:
api= tweepy.API(auth, wait_on_rate_limit=True)
我也更改了这行代码:
tweets = tweepy.Cursor(api.search,
q=str(n) + '-filter:retweets',
lang='en',
since='2018-01-01').items(10000)
对此:
# note the count, which helped increase performance.
tweets = tweepy.Cursor(api.search,
q=str(n) + '-filter:retweets',
count=100,
since='2018-01-01',
lang="en").items(500)
总体而言,您的原始代码在这两次修改时运行得更快,但仍需要更多调整。快乐编码......