如何循环遍历字符串列表并提取三个不同的变量?我试图解决的问题是类(class)的一部分,但没有给出解决方案。
问题:如何循环一组推文并取出三个不同的变量:“happy_tweets”、“sad_tweets”和“neutral_tweets”
我在找出循环推文并提取每种类型推文的最佳方法时遇到了很多麻烦。
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:
if happy_words in tweets:
happy_tweets += 1
print(happy_tweets)
最佳答案
我建议使用 set comprehensions 生成每组推文的新列表。就像 list comprehensions 。然后,您可以将原始推文列表的差异与快乐和悲伤推文集的并集相结合。就像这样:
happy_tweets = {t for t in tweets for w in happy_words if w in t}
sad_tweets = {t for t in tweets for w in sad_words if w in t}
neutral_tweets = set(tweets) - (happy_tweets | sad_tweets)
print(list(happy_tweets))
print(list(sad_tweets))
print(list(neutral_tweets))
这给出:
['Apple announces the release of the new iPhone 12. Fans are excited.', "I'm really excited to learn Python with @JovianML #zerotopandas", 'Spent my day with family!! #happy', 'Freecodecamp has great coding tutorials. #skillup', 'Wow, what a great day today!! #sunshine', 'This is a really nice song. #linkinpark']
['I feel sad about the things going on around us. #covid19', 'Why do bad things happen to me?']
['Check out my blog post on common string operations in Python. #zerotopandas', 'The python programming language is useful for data science']
此处使用集合来代替 happy_tweets
和 sad_tweets
中的列表的原因是为了防止列表中有多个单词与推文字符串匹配时出现重复。一个稍微更有效的方法,虽然更冗长,是将它们移到实际的 for 语句中,并在第一个单词匹配时中断。但这对于时间复杂度来说并不是一个显着的变化。
顺便说一句,union 的原因是操作必须基于 operator precedence 进行分组
关于python - 如何循环遍历列表并取出几个不同的变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73333432/