開始使用免費開始

太喜歡了!

你仍在進行 Twitter 情緒分析專案。首先,你想找出關於電影和音樂會的正向推文。

你打算找出所有包含 love、like 或 enjoy 這些字的句子,並把該字擷取下來。你也會把範圍限制在同時包含 movie 或 concert 的推文,並把該字放在另一個群組中。此外,你還要儲存電影或音樂會的名稱。

例如,若有句子:I love the movie Avengers.,你需要比對並擷取 love。你也需要比對並擷取 movie。之後,再比對並擷取直到句點為止的所有內容。

清單 sentiment_analysis(包含三則推文的文字)以及 re 模組已載入到你的工作階段。你可以在 IPython Shell 中使用 print() 檢視資料。

本練習屬於課程

Python 中的正規表示法

檢視課程

練習說明

  • 完成正規表示式以擷取 lovelikeenjoy。比對並擷取 movieconcert。再比對並擷取出現在 . 之前的所有內容。
  • sentiment_analysis 的每個元素中,找出該正規表示式的所有符合,並指派給 positive_matches
  • 完成 .format() 方法,將 sentiment_analysis 各元素中 positive_matches 的結果印出。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Write a regex that matches sentences with the optional words
regex_positive = r"____.+?____\s____\."

for tweet in sentiment_analysis:
	# Find all matches of regex in tweet
    positive_matches = re.____(____, ____)
    
    # Complete format to print out the results
    print("Positive comments found ____".format(____))
編輯並執行程式碼