蓝桥杯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.运行结果

相关推荐
阿正的梦工坊10 分钟前
Sliding Window Attention(滑动窗口注意力)解析: Pytorch实现并结合全局注意力(Global Attention )
人工智能·pytorch·python
喜-喜33 分钟前
Python pip 缓存清理:全面方法与操作指南
python·缓存·pip
rgb2gray34 分钟前
GeoHD - 一种用于智慧城市热点探测的Python工具箱
人工智能·python·智慧城市
MZWeiei1 小时前
Matplotlib,Streamlit,Django大致介绍
python·django·matplotlib
游客5202 小时前
自动化办公|xlwings生成图表
python·自动化
ylfhpy2 小时前
Python常见面试题的详解16
开发语言·python·面试
蹦蹦跳跳真可爱5892 小时前
Python----PyQt开发(PyQt高级:手搓一个音乐播放器)
python·pyqt
高力士等十万人2 小时前
OpenCV对比度增强
人工智能·python·opencv
宝哥的菜鸟之路2 小时前
Python 数据分析概述 ①
开发语言·python·数据分析
全栈若城2 小时前
03 Python字符串与基础操作详解
java·开发语言·python