开始使用免费开始使用

重复——又重复的字符

回到情感分析!您的下一个任务是替换推文中出现的拉长词。我们将"拉长词"定义为:包含某个字符连续重复 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") 
编辑并运行代码