蓝桥杯day03——Bigram 分词

1.题目

给出第一个词 first 和第二个词 second,考虑在某些文本 text 中可能以 "first second third" 形式出现的情况,其中 second 紧随 first 出现,third 紧随 second 出现。

对于每种这样的情况,将第三个词 "third" 添加到答案中,并返回答案。

示例 1:

复制代码
输入:text = "alice is a good girl she is a good student", first = "a", second = "good"
输出:["girl","student"]

示例 2:

复制代码
输入:text = "we will we will rock you", first = "we", second = "will"
输出:["we","rock"]

提示:

  • 1 <= text.length <= 1000
  • text 由小写英文字母和空格组成
  • text 中的所有单词之间都由 单个空格字符 分隔
  • 1 <= first.length, second.length <= 10
  • firstsecond 由小写英文字母组成

2.解析

  • text(一个字符串,我们要在其中查找特定的字符串),first(第一个字符串)和second(第二个字符串)。这个函数的目标是在text中查找所有firstsecond的连续出现后的第三个词 "third" ,并返回这些第三个词 "third" 的列表。
  • s=first + " " + second:定义一个字符串s,是firstsecond的连接,中间有一个空格。
  • ls = re.findall("[a-z]*" + s + " " + "[a-z]+", text):使用正则表达式在text中查找所有以字母开头,接着是s,然后是一个或多个字母的组合。结果存储在列表ls中。
  • ls1 = re.findall(s + " " + s + " " + "([a-z]+)", text):在文本中查找所有s连续出现两次,中间有一个空格和一个或多个字母的组合。结果存储在列表ls1中。
  • if first==second::如果第一个和第二个字符串相同,则执行以下操作。
  • ls1+=re.findall(second + " " + s + " " + "([a-z]+)",text):在文本中查找所有与之前相同的字符串(因为firstsecond相同),即查找所有连续出现两次的字符串,中间有一个空格和一个或多个字母的组合。找到的结果添加到ls1中。

3.python代码

python 复制代码
class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> list[str]:
        import re
        s=first + " " + second

        ls = re.findall("[a-z]*" + s + " " + "[a-z]+", text)
        ls1 = re.findall(s + " " + s + " " + "([a-z]+)", text)

        if first==second:
            ls1+=re.findall(second + " " + s + " " + "([a-z]+)",text)

        for x in ls:
            if x.startswith(s):
                ls1 += re.findall(s + " " + "([a-z]+)", x)

        return ls1

4.运行结果

相关推荐
无心水17 分钟前
【Python实战进阶】2、Jupyter Notebook终极指南:为什么说不会Jupyter就等于不会Python?
python·jupyter·信息可视化·binder·google colab·python实战进阶·python工程化实战进阶
上班日常摸鱼1 小时前
Shell脚本基础教程:变量、条件判断、循环、函数实战(附案例)
python
无心水2 小时前
【Python实战进阶】5、Python字符串终极指南:从基础到高性能处理的完整秘籍
开发语言·网络·python·字符串·unicode·python实战进阶·python工业化实战进阶
2301_807583232 小时前
了解python,并编写第一个程序,常见的bug
linux·python
小白学大数据2 小时前
构建混合爬虫:何时使用Requests,何时切换至Selenium处理请求头?
爬虫·python·selenium·测试工具
2401_827560202 小时前
【Python脚本系列】PyAudio+librosa+dtw库录制、识别音频并实现点击(四)
python·语音识别
BBB努力学习程序设计2 小时前
Python自动化脚本:告别重复劳动
python·pycharm
BBB努力学习程序设计2 小时前
Python函数式编程:优雅的代码艺术
python·pycharm
2501_940943912 小时前
体系课\ Python Web全栈工程师
开发语言·前端·python
田姐姐tmner3 小时前
Python切片
开发语言·python