如何遍历推文列表提取快乐、悲伤、中性推文计数三类变量
问题解决:推文情感分类统计
你的代码核心问题在于判断逻辑错误,happy_words in tweets是在检查整个happy_words列表是否是tweets列表的元素,这显然永远不会成立,所以统计结果一直是0。另外你也没处理大小写匹配的问题,也没实现sad和neutral推文的统计逻辑。
下面是修正后的完整代码:
tweets = [ "Wow, what a great day today!! #sunshine", "I feel sad about the things going on around us. #covid19", "I'm really excited to learn Python with @JovianML #zerotopandas", "This is a really nice song. #linkinpark", "The python programming language is useful for data science", "Why do bad things happen to me?", "Apple announces the release of the new iPhone 12. Fans are excited.", "Spent my day with family!! #happy", "Check out my blog post on common string operations in Python. #zerotopandas", "Freecodecamp has great coding tutorials. #skillup" ] happy_words = ['great', 'excited', 'happy', 'nice', 'wonderful', 'amazing', 'good', 'best'] sad_words = ['sad', 'bad', 'tragic', 'unhappy', 'worst'] happy_tweets = 0 sad_tweets = 0 neutral_tweets = 0 for tweet in tweets: # 转小写避免大小写干扰 tweet_lower = tweet.lower() # 检查是否包含任意快乐词汇 is_happy = any(word in tweet_lower for word in happy_words) # 检查是否包含任意悲伤词汇 is_sad = any(word in tweet_lower for word in sad_words) if is_happy: happy_tweets += 1 elif is_sad: sad_tweets += 1 else: neutral_tweets += 1 print(f"快乐推文:{happy_tweets}") print(f"悲伤推文:{sad_tweets}") print(f"中性推文:{neutral_tweets}")
关键修正点:
- 大小写统一:将推文转为小写,确保"Great"和"great"能被正确匹配
- 正确的存在性检查:用
any()函数遍历情感词汇列表,判断推文中是否包含任意一个目标词汇 - 完整的分类逻辑:补充了sad和neutral推文的统计分支,确保所有推文都被归类
运行这段代码会得到正确的统计结果:
快乐推文:6 悲伤推文:2 中性推文:2
内容的提问来源于stack exchange,提问作者pc510895
相关产品推荐
相关产品推荐

