Sean - 1 year ago 169
Python Question

# Python Function That Counts Number of Alphabetic Characters, Keeps Track of How Many Times "e" Appears

Write a function analyze_text that receives a string as input. The function should count the number of alphabetic characters (a through z, or A through Z) in the text and also keep track of how many are the letter 'e' (upper or lowercase).

The function should return an analysis of the text, something like this:

The text contains 240 alphabetic characters, of which 105 (43.75%) are āeā.

I need to make use of the isalpha function, which can be used like this:

``````"a".isalpha() # => evaluates to True
"3".isalpha() # => evaluates to False
"&".isalpha() # => False
" ".isalpha() # => False

mystr = "Q"
mystr.isalpha() # => True
``````

The function should pass the following tests:

``````from test import testEqual

text1 = "Eeeee"
answer1 = "The text contains 5 alphabetic characters, of which 5
(100.0%) are 'e'."

text2 = "Blueberries are tasteee!"
answer2 = "The text contains 21 alphabetic characters, of which 7
(33.3333333333%) are 'e'."

text3 = "Wright's book, Gadsby, contains a total of 0 of that most
common symbol ;)"

answer3 = "The text contains 55 alphabetic characters, of which 0
(0.0%) are 'e'."

``````

So I tried:

``````def analyze_text(text):

text = input("Enter some text")
alphaChars = len(text)

#count the number of times "e" appears
eChars = text.count('e')

#find percentage that "e" appears
eCharsPercent = eChars / alphaChars

print("The text contains" + alphaChars + "alphabetic characters, of
which" + eChars + "(" + eCharsPercent + ") are 'e'.")

from test import testEqual

text1 = "Eeeee"
answer1 = "The text contains 5 alphabetic characters, of which 5
(100.0%) are 'e'."

text2 = "Blueberries are tasteee!"
answer2 = "The text contains 21 alphabetic characters, of which 7
(33.3333333333%) are 'e'."

text3 = "Wright's book, Gadsby, contains a total of 0 of that most
common symbol ;)"
answer3 = "The text contains 55 alphabetic characters, of which 0
(0.0%) are 'e'."

``````

As you can see, what I tried doesn't make use of the isalpha function (I don't know how / where to use it). Also, the function won't return whether or not the tests were passed. Visualize python doesn't support "test", and the text editor that I'm using in the book says that I have an indentation error (?) I don't know where to start - please help.

Screenshot of Book Text Editor

EDIT: Now receiving "TypeError: cannot concatenate 'str' and 'int' objects on line 12" (the line that starts with "print").

Here's an `analyse_text` function that passes the tests:
``````def analyze_text(text):
• count letter `e` (you got that right)
• format string accordignly (used a bit of a hack to get the `33.3333333` right, maybe something better can be done). Getting the exact string is a bit pointless...