简体   繁体   中英

How do I fix this program so I can count the number of letters and how do I count words?

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.

You should pass the string directly to the constructor of Counter

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

To do words, just split on spaces (or maybe periods too_

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

To count characters, you can use regular expressions to remove any non-alphanumeric character, ie:

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

You can use the re module to count words too, by counting the non-empty strings you get from splitting the string at non-alphanumeric characters:

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

If you want to strip numbers too, just use [\\W\\d] instead of [\\W] .

You can find more on regular expressions here .

Don't go over your head with this one and use a good old list comprehension:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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