如何修复此程序,以便计算字母数量以及如何计算字数?

时间:2014-03-23 12:49:56

标签: python

如何修复此程序,以便计算字母数量以及如何计算字数?

import collections as c
text = input('Enter text')
print(len(text))
a = len(text)
counts = c.Counter(a)
print(counts)
spaces = counts(' ')
print(specific)
print(a-spaces)
#I want to count the number of letters so I want the amount of characters - the amount of             
#spaces.

3 个答案:

答案 0 :(得分:0)

您应该将字符串直接传递给Counter

的构造函数
cc = c.Counter( "this is a test" )
cc[" "] # will be 3

做单词,只是拆分空格(或者也可以是句号_

cc = c.Counter( "this is a test test".split( " " ) )
cc[ "test" ] # will be 2

答案 1 :(得分:0)

要计算字符数,您可以使用正则表达式删除任何非字母数字字符,即:

import re
print(re.sub("[\W]", "", text))

您也可以使用re模块计算单词,方法是计算以非字母数字字符分割字符串所得到的非空字符串:

print([word for word in re.split("[\W]", text) if len(word) > 0])

如果您想要删除数字,只需使用[\W\d]代替[\W]

您可以在正则表达式here上找到更多信息。

答案 2 :(得分:0)

不要过度使用这个并使用一个好的旧列表理解:

text = raw_input('Enter text') #or input(...) if you're using python 3.X
number_of_non_spaces = len([i for i in text if i != " "])
number_of_spaces = len(text) - number_of_non_spaces
相关问题