如何计算字符串中没有空格的字母数?

时间:2013-08-27 00:44:39

标签: python

这是我的解决方案,导致错误。返回0

PS:我仍然喜欢修复我的代码:)

from collections import Counter
import string


def count_letters(word):
    global count
    wordsList = string.split(word)
    count = Counter()
    for words in wordsList:
        for letters in set(words):
            return count[letters]

word = "The grey old fox is an idiot"
print count_letters(word)

13 个答案:

答案 0 :(得分:20)

def count_letters(word):
    return len(word) - word.count(' ')

或者,如果您有多个要忽略的字母,则可以过滤字符串:

def count_letters(word):
    BAD_LETTERS = " "
    return len([letter for letter in word if letter not in BAD_LETTERS])

答案 1 :(得分:11)

使用sum函数解决方案:

sum(c != ' ' for c in word)

它是一种内存有效的解决方案,因为它使用generator而不是创建临时列表,然后计算它的总和。

值得一提的是,c != ' '会返回True or False,这是bool类型的值,但boolint的子类型},所以你可以总结bool值(True对应1False对应0

您可以使用mro方法检查无效性:

>>> bool.mro() # Method Resolution Order
[<type 'bool'>, <type 'int'>, <type 'object'>]

您在此处看到boolint的子类型,它是object的子类型。

答案 2 :(得分:6)

MattBryant的答案很好,但是如果你想排除更多类型的字母而不仅仅是空格,它就会变得笨重。以下是使用Counter的当前代码的变体:

from collections import Counter
import string

def count_letters(word, valid_letters=string.ascii_letters):
    count = Counter(word) # this counts all the letters, including invalid ones
    return sum(count[letter] for letter in valid_letters) # add up valid letters

示例输出:

>>> count_letters("The grey old fox is an idiot.") # the period will be ignored
22

答案 3 :(得分:4)

使用正则表达式计算字符串中的字母数。

import re
s = 'The grey old fox is an idiot'
count = len(re.findall('[a-zA-Z]',s))

答案 4 :(得分:3)

好的,如果那就是你想要的,我会采取以下措施来修复你现有的代码:

from collections import Counter

def count_letters(words):
    counter = Counter()
    for word in words.split():
        counter.update(word)
    return sum(counter.itervalues())

words = "The grey old fox is an idiot"
print count_letters(words)  # 22

如果您不想计算某些非空白字符,那么您需要删除它们 - 如果不是更早的话,请在for循环内删除。

答案 5 :(得分:3)

另一个单线解决方案:

def count_letters(word):  return len(filter(lambda x: x not in " ", word))

这可以通过使用过滤器函数来实现,它允许您选择列表中的元素,这些元素在传递给作为第一个参数传递的布尔值函数时返回true。我正在使用lambda函数为此目的制作一个快速,一次性的函数。

>>> count_letters("This is a test")
11

您可以轻松扩展此选项以排除您喜欢的任何字符选择:

def count_letters(word, exclude):  return len(filter(lambda x: x not in exclude, word))

>>> count_letters ("This is a test", "aeiou ")
7

编辑:但是,你想让自己的代码工作,所以这里有一些想法。第一个问题是您没有为Counter对象设置列表进行计数。但是,由于您正在查找字母总数,因此需要将这些单词重新连接在一起,而不是单独计算每个单词。循环添加每个字母的数量并不是必需的,因为你可以提取值列表并使用“sum”来添加它们。

这是一个与我的代码尽可能接近的版本,没有循环:

from collections import Counter
import string

def count_letters(word):
   wordsList = string.split(word)
   count = Counter("".join(wordsList))
   return sum(dict(count).values())

word = "The grey old fox is an idiot"
print count_letters(word)

编辑:在回应评论,询问为什么不使用一个for循环,这是因为它是没有必要的,而且在许多情况下,使用许多隐性的方式来执行Python的重复性任务可以更快,更简单的阅读,更存储器效率。

例如,我可以写

joined_words = []
for curr_word in wordsList:
    joined_words.extend(curr_word)
count = Counter(joined_words)

但是在这样做的过程中,我最终分配了一个额外的数组并通过我的解决方案的Python解释器执行循环:

count = Counter("".join(wordsList))

将在一大块优化的编译C代码中执行。我的解决方案不是简化循环的唯一方法,但它是单向的。

答案 6 :(得分:3)

我设法将其浓缩为两行代码:

string = input("Enter your string\n")
print(len(string) - string.count(" "))

答案 7 :(得分:2)

n=str(input("Enter word: ").replace(" ",""))

ans=0
for i in n:
    ans=ans+1
print(ans)    

答案 8 :(得分:0)

我发现这很完美

str = "count a character occurance"
str = str.replace(' ', '')
print (str)
print (len(str))

答案 9 :(得分:0)

def count_letter(string):
    count = 0
    for i in range(len(string)):
        if string[i].isalpha():
            count += 1
    return count


print(count_letter('The grey old fox is an idiot.'))

答案 10 :(得分:0)

word_display = ""
for letter in word:
    if letter in known:
        word_display = "%s%s " % (word_display, letter)
    else:
        word_display = "%s_ " % word_display
return word_display

答案 11 :(得分:0)

string=str(input("Enter any sentence: "))
s=string.split()
a=0
b=0

for i in s:
    a=len(i)
    b=a+b

print(b)

它可以完美地工作而无需计算字符串的空格

答案 12 :(得分:-3)

尝试使用...

resp = input("Hello, I am stuck in doors! What is the weather outside?")
print("You answered in", resp.ascii_letters, "letters!")

没有为我工作,但应该为一些随机的人工作。

相关问题