比特币新闻情感分析代码触发TypeError,请求故障排查与修复
解决比特币新闻情感分析代码中的TypeError问题
嘿,我来帮你搞定这个TypeError!根据你的代码和场景,这个错误大概率是因为News API返回的部分文章里description字段是空值(None)——毕竟不是所有新闻都有描述文本,而TextBlob()只能接收字符串类型的输入,直接传None就会触发类型错误。
下面是两种可行的修复方案,你可以选一种适合你的:
方案1:在apply时直接处理空值
修改计算polarity和subjectivity的两行代码,加入空值判断逻辑,确保只给TextBlob传有效的字符串:
# 处理polarity,空值时返回0.0 news['polarity'] = news.apply( lambda x: TextBlob(x['description']).sentiment.polarity if x['description'] is not None else 0.0, axis=1 ) # 处理subjectivity,空值时返回0.0 news['subjectivity'] = news.apply( lambda x: TextBlob(x['description']).sentiment.subjectivity if x['description'] is not None else 0.0, axis=1 )
方案2:先预处理填充空值
先把所有空的description填充成空字符串,这样后续TextBlob处理时就不会报错(空字符串的情感极性和主观性都是0.0):
# 先填充空的description字段 news['description'] = news['description'].fillna('') # 再计算情感指标 news['polarity'] = news.apply(lambda x: TextBlob(x['description']).sentiment.polarity, axis=1) news['subjectivity'] = news.apply(lambda x: TextBlob(x['description']).sentiment.subjectivity, axis=1)
另外,你也可以提前过滤掉没有description的文章,用news = news[news['description'].notna()],这样后续处理的都是有有效描述的内容,不过这种方式会丢失部分数据,看你的需求选择。
把上面的修改替换到原代码对应的位置,应该就能解决TypeError问题啦!
内容的提问来源于stack exchange,提问作者Matthias
相关产品推荐
相关产品推荐

