计数变量递增一次

时间:2018-01-28 17:58:36

标签: python

def countDog1(st):
    count = 0
    for word in st.lower().split():
        if word == 'dog':
            count += 1
    return count

我想增加count的值,但它只能运行一次。

2 个答案:

答案 0 :(得分:0)

我认为意外行为是由字符串中的非字母数字字符引起的:

'hello dog dog!'.lower().split()

返回

['hello', 'dog', 'dog!']

因此“狗”只会被计算一次。以下是有关如何使用re解决该问题的示例:

import re

def countDog1(st):
    count = 0
    for word in st.lower().split():
        if word == 'dog':
            count += 1
    return count

print('Function countDog1: ' + str(countDog1('hello dog I am a dog!')))

def countDog2(st):
    count = 0
    st = re.sub(r'([^\s\w]|_)+', '', st)
    for word in st.lower().split():
        if word == 'dog':
            count += 1
    return count

print('Function countDog2: ' + str(countDog2('hello dog I am a dog!')))

输出:

Function countDog1: 1
Function countDog2: 2

答案 1 :(得分:0)

你在问题​​中写的功能似乎有效。确保缩进返回标准。你可能在代码中将它缩进了一个级别。