0

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

  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。

4

8 回答 8

1
>>> s = 'bobbbobobboobobookobobbobbboj'
>>> term = 'bob'
sum(1 for i, j in enumerate(s) if s[i:i+len(term)] == term)
6
于 2013-10-28T02:31:12.120 回答
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] 将是“鲍勃”(它以 0 开头)。

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

于 2013-10-28T01:49:34.633 回答
1

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并逐步执行该程序。

于 2017-06-10T12:23:47.040 回答
0

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

如果您想了解如何创建字符串查找功能,那么您需要阅读 字符串搜索算法

于 2013-10-28T01:40:04.290 回答
0

这是基于Brandon对链接问题的回答的实现。

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

保罗的回答已经有了主要要点,但我希望这会有所帮助。

于 2013-10-28T02:07:43.913 回答
0
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   
于 2015-06-21T15:24:35.953 回答
0
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
于 2016-10-23T10:09:03.783 回答
0

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

from re import findall

    def bobcount(word):
        return len(findall(r'(bob)', word.lower()))
于 2017-06-03T05:38:02.827 回答