Python 中 Bigram 之后的出现
pythonserver side programmingprogramming更新于 2025/11/2 11:56:17
假设给出了两个单词。它们是 first 和 second,考虑某些文本中形式为"first second third"的出现,这里第二个紧跟在第一个之后,第三个紧跟在第二个之后。
对于每种情况,将"third"添加到答案中,并显示答案。因此,如果文本类似于"lina is a good girl she is a good song",first = "a",second = "good",则答案将是 [girl, songs]
为了解决这个问题,我们将遵循以下步骤 −
- text := 用空格拆分字符串
- res 是一个空列表
- for i := 0 到文本大小 – 1
- 如果 i + 2 < 文本长度,且 text[i] = 第一行且 text[i + 1] = 第二行,则将 text[i + 2] 附加到 res 中
- 返回 res
示例
让我们看看下面的实现以便更好地理解 −
class Solution(object):
def findOcurrences(self, text, first, second):
text = text.split(" ")
res = []
for i in range(len(text)):
if i+2<len(text) and text[i] ==first and text[i+1]==second:
res.append(text[i+2])
return res
ob1 = Solution()
print(ob1.findOcurrences("lina is a good girl she is a good
singer","a","good"))
输入
"lina is a good girl she is a good singer" "a" "good"
输出
['girl', 'singer']
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

