開始使用免費開始

重複好多次的字元

回到你的情緒分析!下一個任務是取代推文中被拉長的單字。我們將「被拉長的單字」定義為:其中有某個字元連續重複 2 次以上的單字,例如「Awesoooome」。

取代這些單字很重要,因為分類器會把它們視為和原本單字不同的詞,導致原詞頻率降低。

為了找到它們,你會使用擷取群組,並用數字回指。例如 \4

如果你想找到 Awesoooome 的符合,必須先擷取 Awes,接著比對 o 並回指同一個字元,最後再比對 me

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

本練習屬於課程

Python 中的正規表示法

檢視課程

練習說明

  • 依照說明完成正規表示式,以比對被拉長的單字。
  • 在清單 sentiment_analysis 中搜尋其元素是否包含被拉長的單字。將結果指定給 match_elongated
  • 將第 0 個擷取群組指定給變數 elongated_word
  • 列印變數 elongated_word 中的結果。

動手互動練習

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

# Complete the regex to match an elongated word
regex_elongated = r"____(____)____\w*"

for tweet in sentiment_analysis:
	# Find if there is a match in each tweet 
	match_elongated = re.____(____, ____)
    
	if match_elongated:
		# Assign the captured group zero 
		elongated_word = match_elongated.____(____)
        
		# Complete the format method to print the word
		print("Elongated word found: {____}".format(word=____))
	else:
		print("No elongated word found") 
編輯並執行程式碼