如何比较两个列表?

斯瓦加特·辛格
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']

问题:确定数据集中可以归类为快乐的推文数量。

我的代码:

number_of_happy_tweets = 0
 
for i in tweets:
  for x in i:
    if x in happy_words:
      number_of_happy_tweets += len(x)

为什么这段代码不起作用??????

穆罕默德·沙法尔

嗨,在第二个循环中,您正在迭代元素(字母),而不是单词。迭代单词使用 split() 如下所示,还请注意,number_of_happy_tweets每次增加一,但长度不是:

for i in tweets:
    for x in i.split():
        if x in happy_words:
            number_of_happy_tweets += 1

但请注意,如果在一条推文中您有两个(或更多)快乐词,则代码会将其计为两个,或者即使快乐词与其他符号(如 #)组合,它也不会以这种方式计算,因此我建议使用以下代码:

for tweet in tweets:
    if any(happy_word in tweet for happy_word in happy_words):
        number_of_happy_tweets += 1

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章