繁体   English   中英

如何修复此程序,以便可以计算字母数和单词数?

[英]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

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

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

您也可以使用re模块对单词进行计数,方法是对通过将字符串拆分为非字母数字字符而获得的非空字符串进行计数:

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

如果您也要去除数字,则只需使用[\\W\\d]而不是[\\W]

您可以在这里找到更多有关正则表达式的信息

不要为此烦恼,而要使用良好的旧列表理解:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM