0

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.
Lafexlos
  • 7,618
  • 5
  • 38
  • 53
user3370908
  • 29
  • 1
  • 7

3 Answers3

0

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
0

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

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.

Roberto
  • 2,696
  • 18
  • 31
0

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
Ketouem
  • 3,820
  • 1
  • 19
  • 29