我必须编写一个接收字符串作为输入的函数。 我的函数应该计算文本中字母字符(a到z,或者a到z)的数量,并跟踪字母“e”(大写或小写)出现的次数。在
我的函数应该返回对文本的分析,如下所示:
The text contains 240 alphabetic characters, of which 105 (43.75%) are ‘e’.
我需要使用str.isalpha
函数,应该这样使用:
"a".isalpha() # => evaluates to True
"3".isalpha() # => evaluates to False
"&".isalpha() # => False
" ".isalpha() # => False
mystr = "Q"
mystr.isalpha() # => True
我正在努力使用.isalpha函数来区分字母字符和特殊字符,例如:",?!/"
…等等。我只是不太确定如何使用它。我看过Stackoverflow,并试图用一些人使用它的方式来使用它。这是我目前为止的代码:
我的字符串应该通过以下测试:
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)
到目前为止,我已经通过了第一个测试,然后我得到了一个错误:
Error
UnboundLocalError: **local variable 'result' referenced before assignment on line 10**
Description
undefined
To Fix
undefined
print()
函数在控制台中写入一个字符串,即“prints”,这与函数中的return
不同。您需要返回正在打印的字符串。在另一个错误发生在第三个测试用例中,因为您没有“e”,因此您除以零。在
修复方法是使用
if char_e
:不过,有些评论:
您没有给
"".join(i for i in text if i.isalpha())
赋值。我在上面修好的。您可以使用}。
text.lower().count('e')
代替计数e
和{您不需要计数
''
,只需使用len()
来计算所有剩余字符。print
返回None
,因此您总是返回None
。当您多次使用字符串加法时,可以将其替换为以下格式:
^{pr2}$最好是:
更新后的函数如下所示:
相关问题 更多 >
编程相关推荐