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

查看:36
本文介绍了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天全站免登陆