Python计数字符串

时间:2014-02-20 14:40:26

标签: python string for-loop

我必须定义一个名为letterCount的函数,其中它返回一个整数,表示函数中有一个字符串的次数。出于某种原因,它返回2,我应该返回7

def letterCount(text,collection):
    for collection in text:
        if collection in text:
           return len(collection) + 1
seuss = 'The cat in a hat came back'
letters = 'ac'
print(letterCount(seuss,letters))

6 个答案:

答案 0 :(得分:2)

也许你想要这个:

def letterCount(text,collection):
    res = 0
    for c in text:
        if c in collection:
            res = res + 1
    return res
seuss = 'The cat in a hat came back'
letters = 'ac'
print(letterCount(seuss,letters))

您在collection中定义变量for collection in text:,它将变量隐藏在def letterCount(text,collection)中。

答案 1 :(得分:0)

如果您想计算字符lettersseuss中出现的次数:

def letterCount(text,collection):
    count = 0

    for i in range(0, len(text) - len(collection)):
        if collection == text[i:i + len(collection)]:
            count += 1

    return count

seuss = 'The cat in a hat came back'
letters = 'ac'
print(letterCount(seuss,letters))

如果您想计算lettersseuss中每封字母的出现次数:

def letterCount(text,collection):
    count = 0

    for i in range(0, len(text)):
        for c in collection:       
            if c == text[i]:
                count += 1

    return count

seuss = 'The cat in a hat came back'
letters = 'ac'
print(letterCount(seuss,letters))

答案 2 :(得分:0)

我认为你编写的python代码的语法是错误的。这很可能是你想要的

def letterCount(text,collection):
  for collection in text:
    if collection in text:
        return len(collection) + 1
seuss = 'The cat in a hat came back'
Letters = 'ac'
print(letterCount(seuss,Letters))

你的问题也不清楚。你能详细说明吗?如果您想要的是计算字符串中的单词数 这就足够了

print len(seuss.split(' '))

答案 3 :(得分:0)

假设您要计算句子中的字母数,我会这样做:

def letterCount(text,collection):
  lettercount = 0
  for letter in collection:
    lettercount += text.count(letter)
  return lettercount


seuss = 'The cat in a hat came back'
Letters = 'ac'
print(letterCount(seuss,Letters)) # Returns 8

说明:

lettercount = 0将我们的计数器设为0

for letter in collection:在传递给函数的字母列表中创建一个循环。在这种情况下,“a”和“c”

lettercount += text.count(letter)计算每个字母出现在句子中的次数,并将其添加到计数器中。

return lettercount将结果发回。

答案 4 :(得分:0)

试试这个:

import re
def letterCount(text,collection):
    return sum(len(re.findall(c, text)) for c in collection)

# re.findall(c, text) -> find all occurences of letter c in text
# len(...)            -> get the length of the list of all occurrences of c in text
# sum(...)            -> sum up all the partial results

答案 5 :(得分:0)

如果你想知道'a'或'c'进来的次数'戴着帽子的猫回来了',那么:

import collections
def letter_count(text, letters):
    counter = collections.Counter(text)
    return sum(counter.get(letter, 0) for letter in letters)