編寫一個函數analyze_text,它接收一個字符串作爲輸入。函數應計算文本中的字母字符數(a到z或從A到Z),並記錄字母'e'(大寫或小寫)的數量。計算字母數字的Python函數,記錄多少次「e」出現
該函數應返回文本的分析,是這樣的:
文本包含240個字母字符,其中105(43.75%)的是「E」。
我需要使用isalpha功能,它可以這樣使用的:
"a".isalpha() # => evaluates to True
"3".isalpha() # => evaluates to False
"&".isalpha() # => False
" ".isalpha() # => False
mystr = "Q"
mystr.isalpha() # => True
功能應通過以下測試:
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)
所以,我想:
def analyze_text(text):
text = input("Enter some text")
alphaChars = len(text)
#count the number of times "e" appears
eChars = text.count('e')
#find percentage that "e" appears
eCharsPercent = eChars/alphaChars
print("The text contains" + alphaChars + "alphabetic characters, of
which" + eChars + "(" + eCharsPercent + ") are 'e'.")
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)
正如你所看到的,我嘗試過的並不使用isalpha函數(我不知道如何/在哪裏使用我T)。此外,無論測試是否通過,函數都不會返回。可視化python不支持「測試」,我在書中使用的文本編輯器說我有縮進錯誤(?)我不知道從哪裏開始 - 請幫助。
Screenshot of Book Text Editor
EDIT:現在接收 「類型錯誤:不能連接於線12 'STR' 和 'INT' 對象」(即與 「打印」 開頭的行)。
in analyse_text print語句在2行中沒有反斜槓。這是您的其中一個錯誤... –
縮進錯誤意味着您沒有正確縮進您的代碼。由於Python使用縮進而不是大括號({,})對塊進行分組,因此需要確保正確使用空格和製表符。不要混合標籤和空格,並且始終使用相同數量的標籤/空格。 – anroesti
@ Jean-FrançoisFabre你是對的我錯過了一個「)」。我解決了這個問題,現在我收到一條新的錯誤消息:TypeError:不能連接第12行的'str'和'int'對象。這是以「print」開頭的行。 – Sean