You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过循环实现推特情感分析中的中性推文识别?

筛选中性推文解决方案

原始数据集与关键词列表

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']

实现思路

中性推文的判定标准是:既不包含任何正向关键词,也不包含任何负向关键词。遍历每条推文时,先统一转为小写避免大小写匹配问题,再分别检查是否存在正向/负向词,同时不满足两者的即为中性推文。

代码实现

方法1:循环遍历写法

neutral_tweets = []

for tweet in tweets:
    tweet_lower = tweet.lower()
    # 检查是否含正向词
    has_happy = any(word in tweet_lower for word in happy_words)
    # 检查是否含负向词
    has_sad = any(word in tweet_lower for word in sad_words)
    # 既无正向也无负向则加入中性列表
    if not has_happy and not has_sad:
        neutral_tweets.append(tweet)

# 输出结果
print("中性推文:")
for tweet in neutral_tweets:
    print(tweet)

方法2:列表推导式写法(更简洁)

neutral_tweets = [
    tweet for tweet in tweets
    if not any(word in tweet.lower() for word in happy_words)
    and not any(word in tweet.lower() for word in sad_words)
]

# 输出结果
print("中性推文:")
for tweet in neutral_tweets:
    print(tweet)

运行结果

执行代码后会得到以下中性推文:

The python programming language is useful for data science
Check out my blog post on common string operations in Python. #zerotopandas

内容的提问来源于stack exchange,提问作者Aaditya Kale

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 19:48:43