Python中的字符串中的子字符串的重叠计数 [英] Overlapping count of substring in a string in Python

查看:446
本文介绍了Python中的字符串中的子字符串的重叠计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想查找字符串中子字符串的所有计数(重叠和非重叠)。
我发现两个答案其中之一是使用正则表达式,这不是我的意图,而另一个是比我所需要的低效。
我需要类似:

I want to find all the counts (overlapping and non-overlapping) of a sub-string in a string. I found two answers one of which is using regex which is not my intention and the other was much more in-efficient than I need. I need something like:

'ababaa'.count('aba') == 2

str.count()只是计算简单子串。我应该怎么办?

str.count() just counts simple substrings. What should I do?

推荐答案

def sliding(a, n):
    return (a[i:i+n] for i in xrange(len(a) - n + 1))

def substring_count(a, b):
    return sum(s == b for s in sliding(a, len(b)))

assert list(sliding('abcde', 3)) == ['abc', 'bcd', 'cde']    
assert substring_count('ababaa', 'aba') == 2

这篇关于Python中的字符串中的子字符串的重叠计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆