Python 如何计算没有空格的字符串中的字母数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18455222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to count the number of letters in a string without the spaces?
提问by Ali Gajani
This is my solution resulting in an error. Returns 0
这是我的解决方案导致错误。返回 0
PS: I'd still love a fix to my code :)
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)
回答by Matt Bryant
def count_letters(word):
return len(word) - word.count(' ')
Alternatively, if you have multiple letters to ignore, you could filter the string:
或者,如果您要忽略多个字母,则可以过滤字符串:
def count_letters(word):
BAD_LETTERS = " "
return len([letter for letter in word if letter not in BAD_LETTERS])
回答by Blckknght
MattBryant's answer is a good one, but if you want to exclude more types of letters than just spaces, it will get clunky. Here's a variation on your current code using Counter
that will work:
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
Example output:
示例输出:
>>> count_letters("The grey old fox is an idiot.") # the period will be ignored
22
回答by pkacprzak
Simply solution using the sumfunction:
使用sum函数的简单解决方案:
sum(c != ' ' for c in word)
It's a memory efficient solution because it uses a generatorrather than creating a temporary list and then calculating the sum of it.
这是一个内存高效的解决方案,因为它使用生成器而不是创建一个临时列表然后计算它的总和。
It's worth to mention that c != ' '
returns True or False
, which is a value of type bool
, but bool
is a subtype of int
, so you can sum up bool values (True
corresponds to 1
and False
corresponds to 0
)
值得一提的是,c != ' '
returnsTrue or False
是 type 的值bool
,但是bool
是 的子类型int
,所以可以总结一下 bool 值(True
对应1
和False
对应0
)
You can check for an inheretance using the mro
method:
您可以使用以下mro
方法检查继承:
>>> bool.mro() # Method Resolution Order
[<type 'bool'>, <type 'int'>, <type 'object'>]
Here you see that bool
is a subtype of int
which is a subtype of object
.
在这里您会看到,这bool
是一个子类型,int
它是 的子类型object
。
回答by martineau
OK, if that's what you want, here's what I would do to fix your existing code:
好的,如果这就是您想要的,那么我将采取以下措施来修复您现有的代码:
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
If you don't want to count certain non-whitespace characters, then you'll need to remove them -- inside the for
loop if not sooner.
如果您不想计算某些非空白字符,那么您需要删除它们——for
如果不是更早的话,在循环内。
回答by Mark R. Wilkins
For another one-liner solution:
对于另一种单线解决方案:
def count_letters(word): return len(filter(lambda x: x not in " ", word))
This works by using the filter function, which lets you pick the elements of a list that return true when passed to a boolean-valued function that you pass as the first argument. I'm using a lambda function to make a quick, throwaway function for that purpose.
这是通过使用 filter 函数来实现的,它允许您选择列表中的元素,当传递给作为第一个参数传递的布尔值函数时返回 true。为此,我正在使用 lambda 函数来创建一个快速、一次性的函数。
>>> count_letters("This is a test")
11
You could easily extend this to exclude any selection of characters you like:
您可以轻松扩展它以排除您喜欢的任何字符选择:
def count_letters(word, exclude): return len(filter(lambda x: x not in exclude, word))
>>> count_letters ("This is a test", "aeiou ")
7
Edit: However, you wanted to get your own code to work, so here are some thoughts. The first problem is that you weren't setting a list for the Counter object to count. However, since you're looking for the total number of letters, you need to join the words back together again rather than counting each word individually. Looping to add up the number of each letter isn't really necessary because you can pull out the list of values and use "sum" to add them.
编辑:但是,您想让自己的代码工作,所以这里有一些想法。第一个问题是您没有为要计数的 Counter 对象设置列表。但是,由于您要查找字母总数,因此您需要将单词重新连接在一起,而不是单独计算每个单词。循环累加每个字母的数量并不是真正必要的,因为您可以拉出值列表并使用“sum”来添加它们。
Here's a version that's as close to your code as I could make it, without the loop:
这是一个尽可能接近您的代码的版本,没有循环:
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)
Edit: In response to a comment asking why not to use a for loop, it's because it's not necessary, and in many cases using the many implicit ways to perform repetitive tasks in Python can be faster, simpler to read, and more memory-efficient.
编辑:回应询问为什么不使用 for 循环的评论,这是因为它没有必要,并且在许多情况下,使用许多隐式方法在 Python 中执行重复性任务可以更快、更易于阅读且更节省内存.
For example, I could have written
例如,我可以写
joined_words = []
for curr_word in wordsList:
joined_words.extend(curr_word)
count = Counter(joined_words)
but in doing this I wind up allocating an extra array and executing a loop through the Python interpreter that my solution:
但在这样做时,我最终分配了一个额外的数组并通过 Python 解释器执行了一个循环,我的解决方案是:
count = Counter("".join(wordsList))
would execute in a chunk of optimized, compiled C code. My solution isn't the only way to simplify that loop, but it's one way.
将在一段优化的、编译的 C 代码中执行。我的解决方案不是简化该循环的唯一方法,但它是一种方法。
回答by Arundhati
I managed to condense it into two lines of code:
我设法将其压缩为两行代码:
string = input("Enter your string\n")
print(len(string) - string.count(" "))
回答by Thiru G
I found this is working perfectly
我发现这工作得很好
str = "count a character occurance"
str = str.replace(' ', '')
print (str)
print (len(str))
回答by Rishabh Joshi
Counting number of letters in a string using regex.
使用正则表达式计算字符串中的字母数。
import re
s = 'The grey old fox is an idiot'
count = len(re.findall('[a-zA-Z]',s))
回答by Mona Jalal
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.'))
回答by Eddie
Try using...
尝试使用...
resp = input("Hello, I am stuck in doors! What is the weather outside?")
print("You answered in", resp.ascii_letters, "letters!")
Didn't work for me but should work for some random guys.
没有为我工作,但应该为一些随机的人工作。