我如何修复这个程序,以便我可以数字母的数量和我该如何计算单词?

2024-03-28 19:57:31 发布

您现在位置: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.

Tags: ofthetextimport程序数量len数字
3条回答

应该将字符串直接传递给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

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

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上找到更多信息。你知道吗

相关问题 更多 >