我試圖使用以下定義和輔助函數clean_up
來計算列表中每個單詞的平均字符數。列表中每個單詞的平均字符數
定義:
- 令牌是從上線的 調用
split()
文件 - 搭話的字符串是不是完全由標點符號 的非空令牌
- 句子是由字符
!?.
或EOF終止的字符序列,但不包括字符。句子排除兩端的空白,並且不是空字符串。
def clean_up(s):
""" (str) -> str
Return a new string based on s in which all letters have been
converted to lowercase and punctuation characters have been stripped
from both ends. Inner punctuation is left untouched.
>>> clean_up('Happy Birthday!!!')
'happy birthday'
>>> clean_up("-> It's on your left-hand side.")
" it's on your left-hand side"
"""
punctuation = """!"',;:.-?)([]<>*#\n\t\r"""
result = s.lower().strip(punctuation)
return result
我的代碼是:
def avg_word_length(text):
""" (list of str) -> float
Precondition: text is non-empty. Each str in text ends with \n and
text contains at least one word.
Return the average length of all words in text.
>>> text = ['James Fennimore Cooper\n', 'Peter, Paul and Mary\n']
>>> avg_word_length(text):
5.142857142857143
"""
a = ''
for i in range(len(text)):
a = a + clean_up(text[i])
words = a.split()
for word in words:
average = sum(len(word) for word in words)/len(words)
return average
我得到的6.16666值...因爲我的答案。
我正在使用Python 3
爲什麼這個結果會讓你困惑?你知道正確的答案是別的嗎? – 2014-11-01 20:49:29
預期的輸出(5.14 ..)顯然在文檔字符串中給出,這就是OP令人困惑的原因。 – DSM 2014-11-01 20:57:02
你在你的問題中定義了一個使得'1111111111111111111111111111111111111111111111111.1.'合法的句子。你從哪裏得到這個定義?事實是,你無法確定句子在哪裏/是什麼。它的語言是一種非常主觀的東西,被解釋和_vague_。 – sln 2014-11-01 21:17:15