【问题标题】:Finding number of times a substring exists in a string - Python [duplicate]查找字符串中存在子字符串的次数 - Python [重复]
【发布时间】:2018-02-13 05:41:12
【问题描述】:

我正在尝试查找子字符串的 # 次,在这种情况下,'bob' 出现在字符串中。我的解决方案适用于某些字符串,但不适用于所有字符串。例如,下面的答案应该是 7,但我返回的是 5。

有什么想法吗?

谢谢

s = 'bobbisbobobugbobobbobbobo'
print('Number of times bob occurs is: ', s.count('bob'))

【问题讨论】:

  • count 计算非重叠匹配。这就是为什么它比您在s 中看到的要少。
  • sum('bob' == s[i:i+len('bob')] for i in range(len(s)-(len('bob')-1)))

标签: python string


【解决方案1】:

问题在于s.count() 返回了 [start, end] 范围内子字符串 sub 的非重叠出现次数。

使用正则表达式计算重叠字符串

import re

text = 'bobbisbobobugbobobbobbobo'
print(len(re.findall('(?=bob)', text)))

【讨论】:

  • 谢谢,哥们你能不能告诉我们一件事,string.count和re.findall有什么区别,因为count函数返回不同的值,findall函数返回不同的值,此外在您的代码中,您以这种格式“(?= bob)”传递了子字符串。请您向我们解释一下。为什么你以这种格式传递子字符串我的意思是你能解释一下内部逻辑是什么
【解决方案2】:

您的解决方案不起作用,因为 str.count 不计算重叠匹配。

尽管有很多其他解决方案,但另一种可能的方法是使用高级regex 模块:

import regex as re
s = 'bobbisbobobugbobobbobbobo'
print(len(re.findall("bob", s, overlapped=True)))

# 7

【讨论】:

    【解决方案3】:

    您似乎想要重叠计数。不幸的是,str.count 不会让您到达那里,因为它不会与子字符串搜索重叠。尝试切片和计数。

    这是一个带有collections.Counter 的解决方案,不过只要你正确地分割它,它几乎可以通过任何其他方式完成。

    from collections import Counter
    
    text = 'bobbisbobobugbobobbobbobo'
    term = 'bob'
    c = Counter([text[i : i + len(term)] for i in range(len(text))])
    print(c[term])
    

    7
    

    【讨论】:

      猜你喜欢
      • 2014-02-27
      • 2021-01-11
      • 2014-05-09
      • 2017-04-25
      • 2020-02-24
      • 2013-09-27
      • 1970-01-01
      • 1970-01-01
      • 2021-08-13
      相关资源
      最近更新 更多