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)
為什么這段代碼不起作用??????
uj5u.com熱心網友回復:
您正在迭代推文中的字母并檢查該字母是否在happy_words您需要做的事情中:
for tweet in tweets:
number_of_happy_tweets = any(word in tweet for word in happy_words)
這意味著number_of_happy_tweets每當在推文中找到任何快樂的詞時,您都會增加一。
uj5u.com熱心網友回復:
嗨,在第二個回圈中,您正在迭代元素(字母),而不是單詞。迭代單詞使用 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
uj5u.com熱心網友回復:
問題出在您的代碼中。
您的代碼的第一行很好for i in tweets。
但在第二行,你使用
for i in tweets:
for x in i: # Try to print `x`
print(x) #
W
o
w
,
w
h
a
t
a
.
.
.
Here you got the letter from tweets.
After that, you try to check these letters in your happy_words list.
試試這個代碼。
happy_words = ['great', 'excited', 'happy', 'nice', 'wonderful', 'amazing', 'good', 'best']
number_of_happy_tweets = 0
number_of_happy_tweets = 0
for i in tweets:
for x in happy_words:
if x in i:
number_of_happy_tweets =1
break
uj5u.com熱心網友回復:
形成術語的正則運算式交替,然后使用串列理解以及re.search:
happy_words = ['great', 'excited', 'happy', 'nice', 'wonderful', 'amazing', 'good', 'best']
regex = r'(?:' r'|'.join(happy_words) r')'
num_tweets = len([x for x in tweets if re.search(regex, x)])
print(num_tweets) # 6
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/482183.html
