我是新手Python程序员,需要计算列表中每个单词的平均字符数。
以下是相关定义和辅助函数 clean_up
:
令牌(token)是调用文件行字符串方法split所得到的字符串。
单词(word)是非空的标记,且不完全由标点符号构成。使用辅助函数clean_up
从单词中删除标点符号,并通过str.split
查找标记以寻找文件中的“单词”。
句子是以(但不包括)字符!
、?
、.
或文件结束符为终止符的字符序列,不包含开头或结尾的空格且不为空。
这是我大学计算机科学课程的作业问题。
clean_up
函数如下:
def clean_up(s):
punctuation = """!"',;:.-?)([]<>*#\n\"""
result = s.lower().strip(punctuation)
return result
我的代码是:
def average_word_length(text):
""" (list of str) -> float
Precondition: text is non-empty. Each str in text ends with \n and at
least one str in text contains more than just \n.
Return the average length of all words in text. Surrounding punctuation
is not counted as part of the words.
>>> text = ['James Fennimore Cooper\n', 'Peter, Paul and Mary\n']
>>> average_word_length(text)
5.142857142857143
"""
for ch in text:
word = ch.split()
clean = clean_up(ch)
average = len(clean) / len(word)
return average
我得到了5.0的结果,但是我非常困惑,希望能得到一些帮助 :) PS 我正在使用Python 3
float(len(word))
- Hoopdadyfor
循环中使用yield average
可以创建一个不错的生成器。 - Adam Smithfrom __future__ import division
有效。Python3才是未来!!! :) - Adam Smith