【问题标题】:Determining how many times a substring occurs in a string in Python确定子字符串在 Python 中的字符串中出现的次数
【发布时间】:2012-07-13 16:07:24
【问题描述】:

我试图弄清楚一个字符串在一个字符串中出现了多少次。例如:

nStr = '000123000123'

假设我要查找的字符串是 123。显然它在 nStr 中出现了两次,但我无法在 Python 中实现这个逻辑。我现在得到了什么:

pattern = '123'
count = a = 0
while pattern in nStr[a:]:
    a = nStr[a:].find(pattern)+1
    count += 1
return count

它应该返回的答案是 2。我现在陷入了无限循环。

我刚刚意识到 count 是一种更好的方法,但出于好奇,有没有人看到类似于我已经拥有的方法?

【问题讨论】:

    标签: python string


    【解决方案1】:

    使用str.count:

    >>> nStr = '000123000123'
    >>> nStr.count('123')
    2
    

    您的代码的工作版本:

    nStr = '000123000123'
    pattern = '123'
    count = 0
    flag = True
    start = 0
    
    while flag:
        a = nStr.find(pattern, start)  # find() returns -1 if the word is not found, 
        #start i the starting index from the search starts(default value is 0)
        if a == -1:          #if pattern not found set flag to False
            flag = False
        else:               # if word is found increase count and set starting index to a+1
            count += 1        
            start = a + 1
    print(count)
    

    【讨论】:

    • 计数功能并非在所有情况下都能正常工作。例如:模式 =“323”和 nStr =“10032323000123”。如您所见, 323 在主字符串中出现了 2 次。但是count的结果是1。所以第二种解是对的。
    【解决方案2】:

    count() 和此处显示的其他方法的问题在于子字符串重叠的情况。

    例如:"aaaaaa".count("aaa") 返回 2

    如果您希望它返回 4 [(aaa)aaa, a(aaa)aa, aa(aaa)a, aaa(aaa)],您可以尝试以下操作:

    def count_substrings(string, substring):
        string_size = len(string)
        substring_size = len(substring)
        count = 0
        for i in xrange(0,string_size-substring_size+1):
            if string[i:i+substring_size] == substring:
                count+=1
        return count
    
    count_substrings("aaaaaa", "aaa")
    # 4
    

    不确定是否有更有效的方法,但我希望这能阐明count() 的工作原理。

    【讨论】:

    • 请注意,在 Python 3 中 xrange() 已重命名为 range()。
    【解决方案3】:
    import re
    
    pattern = '123'
    
    n =re.findall(pattern, string)
    

    我们可以说子串'pattern'在'string'中出现了len(n)次。

    【讨论】:

    • 计算没有重叠的计数!
    【解决方案4】:

    如果您正在寻找如何解决重叠案例的问题。

    s = 'azcbobobegghaklbob'
    str = 'bob'
    results = 0
    sub_len = len(str) 
    for i in range(len(s)):
        if s[i:i+sub_len] == str: 
            results += 1
    print (results)
    

    将导致 3,因为:[azc(bob)obegghaklbob] [azcbo(bob)egghaklbob] [azcbobobegghakl(bob)]

    【讨论】:

      【解决方案5】:

      我很新,但我认为这是一个很好的解决方案?也许吧?

      def count_substring(str, sub_str):
          count = 0
          for i, c in enumerate(str):
              if sub_str == str[i:i+2]:
                  count += 1
          return count
      

      【讨论】:

        【解决方案6】:

        string.count(substring) 在重叠的情况下没有用。

        我的做法:

        def count_substring(string, sub_string):
        
            length = len(string)
            counter = 0
            for i in range(length):
                for j in range(length):
                    if string[i:j+1] == sub_string:
                        counter +=1
            return counter
        

        【讨论】:

          【解决方案7】:

          您不会在每个循环中更改a。你应该输入:

          a += nStr[a:].find(pattern)+1
          

          ...而不是:

          a = nStr[a:].find(pattern)+1
          

          【讨论】:

            【解决方案8】:
            def count_substring(string, substring):
                     c=0
                     l=len(sub_string)
                     for i in range(len(string)):
                             if string [i:i+l]==sub_string:
                                      c=c+1
                     return c
            string=input().strip()
            sub_string=input().strip()
            
            count= count_substring(string,sub_string)
            print(count)
            

            【讨论】:

              【解决方案9】:

              正如@João Pesce 和@gaurav 所提到的,count() 在子字符串重叠的情况下没有用,试试这个...

              def count_substring(string, sub_string):
                  c=0
                  for i in range(len(string)):
                      if(string[i:i+len(sub_string)]==sub_string):
                          c = c+1
                  return c
              

              【讨论】:

                【解决方案10】:
                def countOccurance(str,pat):
                    count=0
                    wordList=str.split()
                    for word in wordList:
                        if pat in word:
                            count+=1
                    return count
                

                【讨论】:

                  【解决方案11】:

                  通常我使用枚举来解决这类问题:

                  def count_substring(string, sub_string):
                          count = 0
                          for i, j in enumerate(string):
                              if sub_string in string[i:i+3]:
                                  count = count + 1
                          return count
                  

                  【讨论】:

                  • @ruddy_simonpour 您可能已经添加了 nStr = '000123000123' 和 pattern = '123' 的 count_substring(nStr, pattern) 产生 2,这是正确的。
                  【解决方案12】:

                  定义计数(子字符串,字符串):

                  count = 0
                  ind = string.find(sub_string)
                  
                  while True:
                      if ind > -1:
                          count += 1
                          ind = string.find(sub_string,ind + 1)
                      else:
                          break
                  return count
                  

                  【讨论】:

                    【解决方案13】:
                    def count_substring(string, sub_string):
                        count = 0
                        len_sub = len(sub_string)
                        for i in range(0,len(string)):
                            if(string[i:i+len_sub] == sub_string):
                                count+=1
                        return count
                    

                    【讨论】:

                    • 与其他答案相比,这有什么优势?
                    猜你喜欢
                    • 2017-06-16
                    • 1970-01-01
                    • 2010-10-20
                    • 1970-01-01
                    • 1970-01-01
                    • 1970-01-01
                    • 2018-04-02
                    相关资源
                    最近更新 更多