Python函数利用.isalph计算字母字符数,跟踪“e”出现的次数

2024-04-19 01:42:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须编写一个接收字符串作为输入的函数。 我的函数应该计算文本中字母字符(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,并试图用一些人使用它的方式来使用它。这是我目前为止的代码:

^{pr2}$

我的字符串应该通过以下测试:

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

Tags: ofthe函数字符串textfalsewhich字母
2条回答

print()函数在控制台中写入一个字符串,即“prints”,这与函数中的return不同。您需要返回正在打印的字符串。在

result = "The text contains" + char + "alphabetic characters, of which" + char_e + "(" + char_ediv + "%" + ")" " are 'e'."
return result

另一个错误发生在第三个测试用例中,因为您没有“e”,因此您除以零。在

修复方法是使用if char_e

def analyze_text(text):
    text = "".join(i for i in text if i.isalpha())
    char = text.count('') - 1
    char_e = text.count('e') + text.count('E')
    if char_e:
        char_ediv = str(char/char_e * 100.0)
    else:
        char_ediv = str(0.0)

不过,有些评论:

  • 您没有给"".join(i for i in text if i.isalpha())赋值。我在上面修好的。

  • 您可以使用text.lower().count('e')代替计数e和{}。

  • 您不需要计数'',只需使用len()来计算所有剩余字符。

  • print返回None,因此您总是返回None

当您多次使用字符串加法时,可以将其替换为以下格式:

^{pr2}$

最好是:

result = ("The text contains {} alphabetic characters, of which {} ({} %) are 'e'."
          "".format(char, char_e, char_ediv))

更新后的函数如下所示:

def analyze_text(text):
    text = "".join([i for i in text if i.isalpha()])
    char = len(text)
    char_e = text.lower().count('e')
    if char_e:
        char_ediv = str(char/char_e * 100.0)
    else:
        char_ediv = str(0.0)

    result = ("The text contains {} alphabetic characters, of which {} ({} %) are 'e'."
              "".format(char, char_e, char_ediv))
    return result

相关问题 更多 >