[英]How do I fix this program so I can count the number of letters and how do I count words?
如何修复此程序,以便可以计算字母数和单词数?
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.
您应该将字符串直接传递给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
不要为此烦恼,而要使用良好的旧列表理解:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.