繁体   English   中英

如何计算Python中字符串中子字符串的出现次数?

[英]How to count number of occurrences of a substring inside a string in Python?

我正在尝试编写一个代码片段,请求用户输入字符串s然后输入子字符串ss 然后程序必须计算sss出现的次数。 例如,如果用户输入s = 'azcbobobegghakl'ss = 'bob' ,则程序应打印:鲍勃发生的次数为:2。

到目前为止,这是我的代码:

def count(s,ss):
    Occurrence = 0
    if ss in s :
        for ss in s :
            Occurrence += 1
    return Occurrence 

#Main program : 
    
s = str(input("Choose a string: "))
    
ss = str(input("Choose a substring:")) 
    
print ("Number of times " + str(ss) + " occurs is : " + str(count(s,ss)) ) 

我想要的输出是这样的:

Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 2

但是我得到了这个:

Choose a string: hellohel
Choose a substring:hel
Number of times hel occurs is : 8

那么有人可以帮我修改此代码以提供所需的输出吗? 提前致谢

你可以使用count

print("hellohel".count("hel"))
2

如果您想计算重叠的出现次数...也许这会有所帮助

def countOverlapping(string, item):
    count = 0
    for i in range(0,len(string)):
        if item in string[i:len(item)+i]:
            count += 1
    return count

print(countOverlapping("ehehe", "ehe"))

输出应该是...

2

这是如何运作的?

正如@SomeDude 提到的,它使用了他所谓的滑动窗口方法

我们取子字符串的长度并检查它是否在每次迭代的字符串“窗口”中:

is ehe in [ehe]he? yes, count += 1
is ehe in e[heh]e? no, pass
is ehe in eh[ehe]? yes, count += 1

您需要采用滑动窗口方法来获取字符串中子字符串的计数。

例子:

字符串:“呵呵”

子字符串:“嗯”

从前 3 个(因为子串的长度是 3 个)字母“ehe”开始——它是我们要找的子串吗? - 是的。

现在留下第一个字母“e”并将字母“he”与下一个字母“h”组合起来形成“heh”这是我们正在寻找的子串吗? - 不

现在留下第一个字母“h”并将字母“eh”与下一个字母“e”组合起来形成“ehe”这是我们正在寻找的子字符串吗? 是的

直到字符串结束并计算“是”的数量

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM