编写一个函数analyze_text,它接收一个字符串作为输入。该函数应计算文本中字母字符(a到z或A到Z)的数量,并跟踪字母“e”(大写或小写)的数量。
该函数应返回文本分析,如下所示:
该文本包含240个字母字符,其中105个(43.75%)为“e”。
我需要使用isalpha函数,可以像这样使用:
"a".isalpha() # => evaluates to True
"3".isalpha() # => evaluates to False
"&".isalpha() # => False
" ".isalpha() # => False
mystr = "Q"
mystr.isalpha() # => True
该功能应通过以下测试:
from test import testEqual
text1 = "Eeeee"
answer1 = "The text contains 5 alphabetic characters, of which 5
(100.0%) are 'e'."
testEqual(analyze_text(text1), answer1)
text2 = "Blueberries are tasteee!"
answer2 = "The text contains 21 alphabetic characters, of which 7
(33.3333333333%) are 'e'."
testEqual(analyze_text(text2), answer2)
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'."
testEqual(analyze_text(text3), answer3)
所以我试过了:
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'."
testEqual(analyze_text(text1), answer1)
text2 = "Blueberries are tasteee!"
answer2 = "The text contains 21 alphabetic characters, of which 7
(33.3333333333%) are 'e'."
testEqual(analyze_text(text2), answer2)
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'."
testEqual(analyze_text(text3), answer3)
正如您所看到的,我尝试的不使用isalpha功能(我不知道如何/在何处使用它)。此外,无论测试是否通过,该函数都不会返回。 Visualize python不支持“test”,我在书中使用的文本编辑器说我有缩进错误(?)我不知道从哪里开始 - 请帮忙。
Screenshot of Book Text Editor
编辑:现在收到“TypeError:无法连接第12行的'str'和'int'对象”(以“print”开头的行)。
答案 0 :(得分:1)
这是一个通过测试的analyse_text
函数:
def analyze_text(text):
filtered = [c.lower() for c in text if c.isalpha()]
cnt = filtered.count('e')
result = "The text contains {} alphabetic characters, of which {} ({}%) are 'e'.".format(len(filtered),cnt,str(100.0*cnt/len(filtered))[:13])
return result
filtered
变量e
(你说得对),创建cnt
计数器33.3333333
权利,也许可以做得更好一些)。获取确切的字符串有点无意义......,创建在{/ li>之后返回行的result
字符串