Python代码报错:tweepy未定义及tweet.text属性不存在问题求助
解决Tweepy情感分析代码的两个错误
错误1:名称'tweepy'未定义
问题原因及解决:
- 未安装Tweepy库:先通过pip安装最新版Tweepy:
pip install tweepy - 缺少API授权初始化:代码直接使用
api对象但未完成Twitter API的授权配置,必须先添加密钥初始化代码(需替换为你在Twitter开发者平台申请的密钥):# 补充API授权 consumer_key = "你的Consumer Key" consumer_secret = "你的Consumer Secret" access_token = "你的Access Token" access_token_secret = "你的Access Token Secret" # 初始化API(v1版本) auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True)
错误2:tweet.text属性未定义
问题原因及解决:
代码中使用了tweepy.Cursor(api.search_users, q=keyword),这个接口是搜索Twitter用户的,返回的是User对象,没有text属性。需替换为搜索推文的接口:
- 若使用Tweepy v1.1,用
api.search_tweets(需确保开发者账号有v1.1搜索权限) - 若使用Tweepy v2,用
client.search_recent_tweets
同时代码还存在未导入SentimentIntensityAnalyzer、函数缩进错误、情感计数逻辑错误等问题,以下是修正后的完整代码:
from textblob import TextBlob import sys import tweepy import matplotlib.pyplot as plt import pandas as pd import numpy as np import os import nltk from nltk.sentiment.vader import SentimentIntensityAnalyzer # 补充导入 import pycountry import re import string # 下载VADER词典(首次运行需要) nltk.download('vader_lexicon') # 补充API授权(替换成你的密钥) consumer_key = "你的Consumer Key" consumer_secret = "你的Consumer Secret" access_token = "你的Access Token" access_token_secret = "你的Access Token Secret" auth = tweepy.OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) api = tweepy.API(auth, wait_on_rate_limit=True) # Sentiment Analysis def percentage(part, whole): return 100 * float(part) / float(whole) keyword = input("请输入要搜索的关键词或话题标签: ") noOfTweet = int(input("请输入要分析的推文数量: ")) # 替换为搜索推文的接口(v1.1版本) tweets = tweepy.Cursor(api.search_tweets, q=keyword, lang="en").items(noOfTweet) positive = 0 negative = 0 neutral = 0 polarity = 0 tweet_list = [] neutral_list = [] negative_list = [] positive_list = [] for tweet in tweets: tweet_text = tweet.text # 现在tweet是推文对象,拥有text属性 tweet_list.append(tweet_text) # TextBlob情感分析 analysis = TextBlob(tweet_text) polarity += analysis.sentiment.polarity # VADER情感分析 score = SentimentIntensityAnalyzer().polarity_scores(tweet_text) neg = score['neg'] neu = score['neu'] pos = score['pos'] # 修正计数逻辑 if pos > neg: positive_list.append(tweet_text) positive += 1 elif pos == neg: neutral_list.append(tweet_text) neutral += 1 else: negative_list.append(tweet_text) negative += 1 # 计算百分比 positive = percentage(positive, noOfTweet) negative = percentage(negative, noOfTweet) neutral = percentage(neutral, noOfTweet) polarity = percentage(polarity, noOfTweet) # 格式化输出 positive = format(positive, '.1f') negative = format(negative, '.1f') neutral = format(neutral, '.1f') print(f"正面情感占比: {positive}%") print(f"中性情感占比: {neutral}%") print(f"负面情感占比: {negative}%")
内容的提问来源于stack exchange,提问作者Ishita Sharma_31
相关产品推荐
相关产品推荐

