如何使用 Python 在字符串中找到重叠序列的数量? [英] How can I find the number of overlapping sequences in a String with Python?
本文介绍了如何使用 Python 在字符串中找到重叠序列的数量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个很长的序列,我想知道一些子序列在这个序列中出现的频率.
I have a long sequence, and I would like to know how often some sub-sequences occur in this sequence.
我知道string.count(s, sub),但是它只计算非重叠序列.
I know string.count(s, sub), but it only counts non-overlapping sequences.
是否存在类似的功能也计算重叠序列?
Does a similar function which also counts overlapping sequences exist?
推荐答案
作为编写自己的搜索功能的替代方法,您可以使用 re
模块:
As an alternative to writing your own search function, you could use the re
module:
In [22]: import re
In [23]: haystack = 'abababa baba alibababa'
In [24]: needle = 'baba'
In [25]: matches = re.finditer(r'(?=(%s))' % re.escape(needle), haystack)
In [26]: print [m.start(1) for m in matches]
[1, 3, 8, 16, 18]
上面打印出所有(可能重叠)匹配项的起始位置.
The above prints out the starting positions of all (potentially overlapping) matches.
如果您只需要计数,以下应该可以解决问题:
If all you need is the count, the following should do the trick:
In [27]: len(re.findall(r'(?=(%s))' % re.escape(needle), haystack))
Out[27]: 5
这篇关于如何使用 Python 在字符串中找到重叠序列的数量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文