【问题标题】:Bob Counter in PythonPython中的鲍勃计数器
【发布时间】:2013-10-28 01:23:55
【问题描述】:

使用 Python 2.7,我试图计算 'bob' 在短语 'bobbbobobboobobookobobbobbboj' 中出现的次数。为此,我编写了以下代码:

  b=0
  string='bobbbobobboobobookobobbobbboj'
  string = string.lower()

  for i in string:
     if(([i:i+3]=="bob") or ([i:i+3]=="BOB")'):
        b=b+1

  print ("Number of times bob occurs is:%s" %b)

但是,当我运行它时,它会输出 0。

【问题讨论】:

  • 欢迎来到 Stack Overflow!感谢您发布您的代码,但请在您的问题中添加更多描述:您遇到什么问题,您期望的结果是什么,到目前为止what have you tried?通过question checklist 将帮助我们更好地回答您的问题。谢谢!
  • 这个程序有很多简单的错误。我真的鼓励你尝试自己解决它们——查看 Python 代码示例,看看它们如何解决问题,并将它们与你正在做的事情进行比较——在此处提问之前。
  • bobbbobobboobobookobobbobbboj 不是字符串,而 "bobbbobobboobobookobobbobbboj" 是。您可能想了解有关字符串切片的知识,请在 google 上搜索。
  • i 一次只有 1 个字符,因此您的 if 将始终失败( 'b' 永远不会等于 'BOB' )。此外,在if 语句之后,您的 6(?) 行上还有缩进错误。

标签: python-2.7


【解决方案1】:

让我们看看我们是否可以帮助您。

你的代码是

s='bobbbobobboobobookobobbobbboj'

 for i in s:

     if(i=='BOB' or i=='bob'):
        b=b+1

考虑这一点很重要——像“s”这样的字符串是一个字符列表。当您执行 for i in s 时,您正在循环遍历每个单独的字符。

在第一次迭代中,i == 'b',在第二次迭代中,它等于 'o',依此类推。

你想要的是检查代码部分的东西。这样做的一种方法是

for i in range(len(s)):
    if s[i:i+4] == "bob":

这样做的原因是 range 按顺序返回一个数字列表,因此它将变为 0、1、2、3... [i:i+4] 部分根据它在字符串中的距离。对于您的字符串 s[0:2] 将是“bob”(它以 0 开头)。

我留下了几个问题......例如,如果你让它运行到最后你会遇到问题(如果 s 是 10 个字符长并且你尝试执行 s[9:12] 你会得到一个错误) ...但这应该可以帮助您继续前进

【讨论】:

  • 不确定您输入的确切内容,但它在我的编辑器中有效。作为说明,我并没有特别注意,但由于“bob”是三个字母长,它应该是 [i:i+3]...
  • @Zak Shaky 这个答案中的代码在语法上是可以的。使用您编写的代码更新您的问题,以便我们查看问题出在哪里。
【解决方案2】:
>>> s = 'bobbbobobboobobookobobbobbboj'
>>> term = 'bob'
sum(1 for i, j in enumerate(s) if s[i:i+len(term)] == term)
6

【讨论】:

    【解决方案3】:

    Python 中的 Bob Counter 程序答案

    s = ('bobobobobobob') #Declare the variable 's' and assign it to a string with 6 bobs in it.
    count = 0 #Declare the variable 'count' and set it equal to 0.
    
    for i in range(len(s)): # for the number i in the length of 's' (12 in our example)
        if s[i:i+3] == "bob": # Example: if s[0:3] == 'bob' is true
            count += 1 # Increase count by 1 to keep track of how many times 'bob' occurs.
      # else :
          # 'count' is not incremented because the string does not equal 'bob'.
          # It most likely says 'obs' in our example instead of 'bob'.
    
        # Next number. On the second loop, i increments from 0 to 1 and it loops through again.
    
    print ('Number of times bob occurs is: ' + str(count)) # Output: 'Number of times bob occurs is: 6'
    

    如果您需要对此进行进一步解释,我建议您将其放入 python IDE 中,例如 http://pythontutor.com/visualize.html#mode=edit 并逐步执行程序。

    【讨论】:

    • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。请阅读此how-to-answer 以提供高质量的答案。
    • 是的,我很久以前就这样做了。有时间我会更新这方面的文档。
    【解决方案4】:

    如果您想以 Pythonic 方式进行操作,那么您需要阅读 string find function

    如果您想了解如何创建字符串查找函数,那么您需要阅读string searching algorithms

    【讨论】:

      【解决方案5】:

      这是基于Brandon's answer 对链接问题的实现。

      def MIT(full_string, substring):
          results = []
          sub_len = len(substring)
          for i in range(len(full_string)):
          # range returns a list of values from 0 to (len(full_string) - 1)
              if full_string[i:i+sub_len] == substring:
              # this is slice notation;
              # it means take characters i up to (but not including) i
              # + the length of th substring
                  results.append(i)
          return results
      
      full_string = "bobBOBBobBoj"
      lower_substring = "bob"
      upper_substring = "BOB"
      lower_occurrence_array = MIT(full_string, lower_substring)
      upper_occurrence_array = MIT(full_string, upper_substring)
      number_of_lower_occurrences = len(lower_occurrence_array)
      number_of_upper_occurrences = len(upper_occurrence_array)
      number_of_occurrences = number_of_lower_occurrences + number_of_upper_occurrences
      
      print ("Number of times bob occurs is: %s" %number_of_occurrences)
      

      结果是

      bob出现的次数是:2

      Paul's answer 的主要要点已经存在,但我希望这会有所帮助。

      【讨论】:

        【解决方案6】:
        start=0
        count=0 
        while start<=len(s):
            n=s.find('b',start,len(s))
            prnt=(s[start:start+3])
            if prnt =='bob':
               start=n+2 
               count+=1
            else:
                start+=1        
        print count   
        

        【讨论】:

        • sexy anwer,如果代码运行不正常但已被 mit 的在线法官接受,请进行一些缩进
        【解决方案7】:
        def bobcount(x):
            bobcounter = 0
            for i in range(len(x)):
                if (x[i:i+3]=="bob") or (x[i:i+3]=="BOB"):
                    bobcounter = bobcounter + 1
            return bobcounter
        

        这是保罗回答的延伸。代码的结果是:

        bobcount("bobobobBOBBOB")
        5
        

        【讨论】:

          【解决方案8】:

          我想我有点晚了,但你可以试试这个:

          from re import findall
          
              def bobcount(word):
                  return len(findall(r'(bob)', word.lower()))
          

          【讨论】:

            猜你喜欢
            • 2011-06-21
            • 2012-11-24
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2022-01-23
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多