运行情感分析脚本时遇textblob模块调用错误求助
解决
'module' object is not callable 错误(TextBlob 情感分析脚本) 这个错误的根源很明确——你混淆了模块名和类名的大小写:
- 你通过
from textblob import TextBlob导入了TextBlob类,但在代码里却用了小写的textblob(tweet)来调用,而textblob是整个模块的名称,不是可调用的类,所以触发了这个类型错误。
修复步骤:
- 修正调用语句的大小写:把代码中所有类似
tweet = textblob(tweet)的行,改成tweet = TextBlob(tweet),确保使用你导入的大写开头的TextBlob类。 - 验证导入语句:确认你的导入语句确实是
from textblob import TextBlob(从你提供的代码片段看这部分是正确的,无需修改)。
修正后的代码片段示例:
import json import csv from textblob import TextBlob # 设置输入输出文件 input_file= "tweets.json" output_file= "results.csv" # 存储所有JSON数据 tweets_novartis = [] with open(input_file) as input_nova: # 读取JSON数据(示例逻辑) tweets_novartis = json.load(input_nova) # 情感分析与结果写入CSV with open(output_file, 'w', newline='') as csvfile: fieldnames = ['tweet_content', 'sentiment_polarity'] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() for tweet in tweets_novartis: # 正确调用TextBlob类进行情感分析 analysis = TextBlob(tweet['text']) # 假设每条推文包含'text'字段 writer.writerow({ 'tweet_content': tweet['text'], 'sentiment_polarity': analysis.sentiment.polarity })
额外验证建议:
可以在终端运行以下命令,快速确认TextBlob在环境中是否正常工作:
python -c "from textblob import TextBlob; print(TextBlob('I love coding!').sentiment)"
如果能输出类似 Sentiment(polarity=0.5, subjectivity=0.6) 的结果,说明安装和导入都没问题。
内容的提问来源于stack exchange,提问作者Ilia
相关产品推荐
相关产品推荐

