我正在處理這個問題,但找不到正確的答案,但我設法挖了一個更大的洞&迷惑自己。因此,如果任何人都可以提供清晰:計數,發現某些字母和百分比
方向:
寫接收一個字符串作爲輸入的功能analyze_text。您的函數應計算文本中的字母字符數(a到z或從A到Z),並記錄字母'e'(大寫或小寫)的數量。
你的功能應該在一個字符串的確切措辭這樣的形式返回文本的分析:「文本包含240個字母字符,其中105(43.75%)的是‘E’」
您將需要使用isalpha函數。
到目前爲止我的代碼: 高清analyze_text(文本): 計數= 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)
你需要顯示你所得到的錯誤,否則你將不會得到任何幫助,但你會得到大量的選票 – aydow
非常接近,但不是打印答案字符串,你需要返回它。此外,通過在同一個循環內增加count和letter_count,您可能會更有效率。 –