【发布时间】:2017-08-14 23:19:35
【问题描述】:
我正在研究这个问题,找不到正确的答案,但我设法挖了一个更大的洞并让自己感到困惑。因此,如果有人可以提供清晰的说明:
方向:
编写一个函数analyze_text,它接收一个字符串作为输入。您的函数应计算文本中字母字符(a 到 z 或 A 到 Z)的数量,并跟踪字母“e”(大写或小写)的数量。
您的函数应该以字符串的形式返回对文本的分析,其措辞完全如下:
“文本包含 240 个字母字符,其中 105 个(43.75%)是‘e’。”
您需要使用 isalpha 函数。
到目前为止我的代码: def 分析文本(文本): 计数 = 0 letter_count = 0
for char in text:
if char.isalpha():
count += 1
for e in text:
if e == "e" or e =="E":
letter_count += 1
p = float(letter_count)/float(count) * 100
analyze.text = "The text contains {0} alphabetic characters, of
which {1} ({2}) are 'e'."
print(analyze_text.format(count += 1, letter_count += 1, p))
TESTS that are given:
# Note that depending on whether you use str.format or
string concatenation
# your code will pass different tests. Code passes either
# tests 1-3 OR tests 4-6.
from test import testEqual
# Tests 1-3: solutions using string concatenation should pass these
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)
# Tests 4-6: solutions using str.format should pass these
text4 = "Eeeee"
answer4 = "The text contains 5 alphabetic characters,
of which 5 (100%) are 'e'."
testEqual(analyze_text(text4), answer4)
text5 = "Blueberries are tasteee!"
answer5 = "The text contains 21 alphabetic characters,
of which 7 (33.33333333333333%) are 'e'."
testEqual(analyze_text(text5), answer5)
text6 = "Wright's book, Gadsby, contains a total of
0 of that most common symbol ;)"
answer6 = "The text contains 55 alphabetic characters,
of which 0 (0%) are 'e'."
testEqual(analyze_text(text6), answer6)
【问题讨论】:
-
你需要展示你遇到了什么错误,否则你不会得到任何帮助,但你会得到很多反对票
-
非常接近,但您不需要打印答案字符串,而是需要返回它。此外,通过在同一个循环中增加 count 和 letter_count 可以提高效率。
标签: python string percentage alpha