0

I have recently started learning python and I am trying to define a function called count_text however I am struggling a lot.

I am aiming to create a function that determines how many letters(lower or uppercase), numbers, spaces or other characters(i.e. #@^) are found in text. The function is supposed to return the four totals in a dictionary with keys of "letters", "numbers", "spaces" and "others".

E.g. count_text('Hello123') should return:

{'letters': 3, 'numbers': 3, 'spaces': 0, 'others': 0}

Any help would be greatly appreciated.

Red
  • 26,798
  • 7
  • 36
  • 58
Nigel Wash
  • 107
  • 7
  • 2
    Have you tried anything so far? – Iain Shelvington Jun 22 '20 at 02:29
  • 1
    "I am trying to define a function called "count_text" however I am struggling a lot." Okay, did you write any code at all? What is the part that you don't understand how to do? When you say that you are "struggling", what are you struggling *with*? For example, do you know how to create any function at all? Do you know how to check if a character is a letter/number/etc.? Do you know how to create a dictionary? Do you know how to *use* a dictionary? – Karl Knechtel Jun 22 '20 at 02:36
  • See this: https://stackoverflow.com/questions/24878174/how-to-count-digits-letters-spaces-for-a-string-in-python – LevB Jun 22 '20 at 02:48

2 Answers2

1

You can use re.findall() with len():

import re

t = "Hello123"

def count_text(t):

    d = {'letters': len(re.findall('[a-zA-Z]',t)),
         'numbers': len(re.findall('[0-9]',t)),
         'spaces': len(re.findall(' ',t)),
         'others': len(re.findall('[^a-zA-z0-9]',t))}

    return d

print(count_text("Hello123"))

Output:

{'letters': 5, 'numbers': 3, 'spaces': 0, 'others': 0}
Red
  • 26,798
  • 7
  • 36
  • 58
1

You can use regex subn. The advantage here is that it will replace the matched character with nothing and then you feed in the new_string to the next step. Maybe a little more efficient, by a tiny bit? :D

def count_text(input):
    import re
    result = {}

    (new_string, result["letters"]) = re.subn(r'[A-Za-z]','',input)
    (new_string, result["numbers"]) = re.subn(r'\d','',new_string)
    (new_string, result["spaces"]) = re.subn(r'\s','',new_string)
    result["others"] = len(new_string)

    return result

To test:

print(count_text("Hello123"))
{'letters': 5, 'numbers': 3, 'spaces': 0, 'others': 0}
print(count_text("Hello 1 2 3"))
{'letters': 5, 'numbers': 3, 'spaces': 3, 'others': 0}
print(count_text("Hello $1 &2 *3!"))
{'letters': 5, 'numbers': 3, 'spaces': 3, 'others': 4}
kamion
  • 461
  • 2
  • 9