如何计算序列出现在python中的给定字符串中的时间?

问题描述 投票:1回答:4

我试图计算一个序列出现在给定字符串中的时间。

def count_seqence(str, seq):
    count = 0
    if seq in str:
        count += 1
    return count
print(count_seqence("the quick brown fox jumps over the lazy dog","he"))

但这只运行一次并且不循环,我怎么能循环并计算出现多少次,因为我知道循环将是每个char而不是seq,这让我感到困惑。

python python-3.x string iteration sequence
4个回答
3
投票

在你的字符串上使用count,它将返回它找到你的参数值seq的时间

def count_seqence(str, seq):
    return str.count(seq)

print count_seqence("kjdsflsdnf lskmfldsknffsdlkfnsldkmf", "ds")

产量

2

4
投票

好吧,因为你使用if而不是循环,这意味着条件是True,因此你增加count,或者它是False,在这种情况下你不执行身体。

如果你想计算数字,你需要一些“循环”机制。这不必是明确的,例如in也隐藏了一个循环。但这只会导致TrueFalse

Non-overlapping (count_seqence('aaaa', 'aa') is 2)

对于非重叠计数,我们可以使用str.count

def count_seqence(text, seq):
    return text.count(seq)

在这种情况下,定义特定功能当然是没有用的。请注意,上述内容仅计算非重叠匹配。例如,当你计算'aa'中的'aaaa'时,你会得到2,而不是3

Overlapping (count_seqence('aaaa', 'aa') is 3)

对于重叠,我们需要执行str.find,并更新“搜索窗口”,直到我们找不到匹配项,如:

def count_seqence(text, seq):
    cnt = 0
    idx = text.find(seq)
    while idx >= 0:
        cnt += 1
        idx = text.find(seq, idx+1)
    return cnt

因此,我们有一个idx存储新匹配发生的索引,每次idx大于或等于0(我们找到匹配)时,我们增加cnt,并将idx更改为下一个匹配。


2
投票

使用string.count方法。检查Python documentation

例:

x = "wip wip I'm a sheep wip"
print(x.count("wip"))

0
投票

对字符串使用count,它将返回找到参数值seq的时间

def count_seqence(str,seq):return str.count(seq)

print count_seqence(“kjdsflsdnf

© www.soinside.com 2019 - 2024. All rights reserved.