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

时间:2017-02-08 02:53:08

标签: python string python-3.x

我必须编写一个接收字符串作为输入的函数。 我的函数应该计算文本中字母字符(a到z或A到Z)的数量,并跟踪字母“e”(大写或小写)出现的次数。

我的函数应该返回对文本的分析,如下所示:

  

该文本包含240个字母字符,其中105个(43.75%)为“e”。

我需要使用str.isalpha函数,它应该像这样使用:

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

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

我正在努力使用.isalpha函数,我假设我们试图用它来区分字母字符和特殊字符,即:",?!/" ...等。我不完全确定如何使用它。我查看了Stackoverflow并试图以我看到有些人使用它的方式使用它。到目前为止,这是我的代码:

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

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

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

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

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

在第三个测试用例中发生了另一个错误,因为你没有“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')代替eE

  • 您无需计算'',只需使用len()计算剩余的所有字符。

  • print返回None,因此您始终返回None

每当您多次使用字符串添加时,您可以使用以下格式替换它:

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

更好的是:

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