Python - 字符串中可能的子字符串计数
本文我们将学习各种方法,使用它们可以对给定字符串中的子字符串进行计数。在使用 Python 时,您可能会遇到需要检查给定单词在句子或任何字符串中出现的次数的情况,因此为了获取较大的主字符串中的子字符串计数,我们将看到一些程序。
方法 1:使用计数方法
这是 Python 中一种简单易用的内置方法,它允许我们计算主字符串中的子字符串。其时间复杂度为 O(n)。
示例
def count_substr_possible(str, substr): count = str.count(substr) return count str="soneduonempaone" substr="one" print("子字符串计数为:",count_substr_possible(str, substr))
输出
子字符串计数为:3
说明
在此函数中,我们传递要计数的字符串和子字符串,并将子字符串赋值给字符串的 count 函数。此 count() 方法将返回出现的总次数。在字符串"soneduonempaone"中,子字符串"one"出现了 3 次,因此结果将为 3,这是字符串内子字符串的总数。
方法 2:使用正则表达式
此方法允许我们处理字符串,例如子字符串匹配和计数。它还具有查找高级模式匹配的功能。
示例
import re def count_substr_possible(str, substring): count = len(re.findall(substring, str)) return count str="soneduonempaone" substr="one" print("子字符串计数为:",count_substr_possible(str, substr))
输出
子字符串计数为:3
解释
在此程序中,我们导入正则表达式库,并使用来自"re"的最终函数,我们找到字符串中子字符串的所有出现位置。 Findcall() 函数返回匹配子字符串的列表,使用 len() 函数,我们找到列表的长度,该列表将作为主字符串中子字符串的总出现次数出现。
方法 3:使用循环和 Find() 函数
在此方法中,我们迭代给定的字符串,并使用 string.find() 函数,我们将找到子字符串的出现位置。
示例
def count_substr_possible(str, substr): count = 0 index = 0 while index != -1: index = str.find(substr, index) if index != -1: count += 1 index += 1 return count str="soneduonempaone" substr="one" print("子字符串计数为:",count_substr_possible(str, substr))
输出
子字符串计数为:1
解释
在上面的程序中,我们创建了两个变量 count 和 index,其中 count 初始化为 0,因为最初子字符串计数为 0。我们将使用 find() 函数检查子字符串的出现情况,从初始索引开始,直到返回 -1。如果出现,例如索引不是 -1,则我们将计数增加一。
方法 4:使用比较和切片
使用此方法,我们执行切片和比较操作来计算字符串中子字符串的总出现次数。
示例
def count_substr_possible(str, substr): count = 0 sub_len = len(substr) for i in range(len(str) - sub_len + 1): if str[i:i + sub_len] == substr: count += 1 return count str="soneduonempaone" substr="one" print("子字符串计数为:",count_substr_possible(str, substr))
输出
子字符串计数为:0
解释
与方法 4 示例相同,我们将创建一个计数变量,初始值为 0,它将保存子字符串的总出现次数。我们将从 0 开始遍历字符串,直到字符串的长度,并从当前位置 i 开始使用子字符串的切片操作。
示例
from itertools import combinations def count_substr_possible(str, substr): count = 0 sub_len = len(substr) for length in range(sub_len, len(str) + 1): for i in range(len(str) - length + 1): sub = ''.join(str[i:i+length]) if sub == substr: count += 1 return count str = "soneduonempaone" substr = "one" print("子字符串计数为:",count_substr_possible(str, substr))
输出
子字符串计数为:3
解释
在此程序中,我们从 itertools 导入了组合。我们的名为 count_substr_possible 的函数接受两个参数,即字符串和子字符串。使用两个嵌套循环,我们将从字符串生成字符组合,外层循环将从子字符串的长度遍历到较大字符串的长度,以生成不同长度的子字符串。然后,我们将使用等号比较子字符串,如果它们相等,则我们将增加到 count 变量中。
因此,我们看到了一些方法,使用这些方法我们可以找到较大字符串中的子字符串总数。我们看到了使用 Python 语言解决问题的四种不同方法。在这四种方法中,string.count() 方法是一种非常简单有效的解决方法,而正则表达式匹配提供了一种非常有效的方法来查找复杂的模式匹配场景。切片和比较也为我们提供了一种非常简单的方法来计算子字符串的出现次数。因此,您可以根据需求和易用性选择任何一种方法,但了解不同的方法有助于更好地学习。