开始使用免费开始使用

查找子串

新的一天开始,您需要继续清洗用于电影预测项目的数据集。探索数据集时,您注意到一个奇怪的模式:在位置 37 的字符与位置 41 的字符之间,出现了一些连续重复的单词。您决定编写一个函数,找出哪些影评存在这种情况,并记住您指定的结束位置是不包含的。如果检测到该单词,您还希望将字符串修改为只保留该单词的一次出现。

请根据说明完成 if-else 语句。

三条影评文本已保存在变量 movies 中。您可以在 IPython Shell 中使用 print(movies) 查看该变量。

本练习是课程的一部分

Python 中的正则表达式

查看课程

练习说明

  • 查找子串 actor 是否出现在索引为 3741(含)的字符之间。若未检测到,则打印语句 Word not found
  • actor 仅连续出现两次,将 actor actor 替换为子串 actor
  • actor 连续出现三次,将 actor actor actor 替换为子串 actor

交互式实操练习

通过完成这段示例代码来试试这个练习。

for movie in movies:
  	# If actor is not found between character 37 and 41 inclusive
    # Print word not found
    if movie.find("____", ____, ____) == ____:
        print("Word not found")
    # Count occurrences and replace two with one
    elif movie.____("____") == 2:  
        print(movie.replace("____", "____"))
    else:
        # Replace three occurrences with one
        print(movie.replace("____", "____"))
编辑并运行代码