def average_word_length(text):
count = 0
for letter in text:
count += 1
return count
text = "This is a brief note"
x = average_word_length(text)
print(x)
我必须打印文本的平均单词长度:这是一个简短的注释。输出必须是3.2(16个字母除以5个单词。如何获得4的输出?
首先,创建一个单词列表:
words = text.split()
然后,找出每个单词的长度:
word_lengths = [len(word) for word in words]
然后,取其平均值:
avg_word_length = sum(word_lengths) / len(word_lengths)
def average_word_length(text):
words = text.split() # ['This', 'is', 'a', 'brief', 'note'], len = 5
# "".join(words)) = 'Thisisabriefnote', len = 16
return len("".join(words)) / len(words)
print(average_word_length('This is a brief note'))
不带join
功能的替代解决方案:
def average_word_length(text):
words = text.split() # ['This', 'is', 'a', 'brief', 'note'], len = 5
# text.replace(' ', '') = 'Thisisabriefnote', len = 16
return len(text.replace(' ', '')) / len(words)
print(average_word_length('This is a brief note'))