average_sentence_length takes a text string and returns its average number of words per sentence. It uses get_sentences to separate sentences, counts nonempty words with split(), and divides the total by the number of sentences. section 11.3.1 section 11.5.7
A short test
average_sentence_length('A pearl! Pearl! Lustrous pearl! Rare. What a nice find.') returns 2.0. The function counts words in each sentence, ignores empty words, and averages the result. section 11.5.7
The sentence rule is deliberately simple: periods, question marks, and exclamation points separate sentences. It can misread abbreviations such as “Mrs.”, but it is considered accurate enough for most of the authorship-identification task. section 11.3.1
Listing 11.9 Average number of words per sentence
def average_sentence_length(text):
'''
text is a string of text.
Return the average number of words per sentence in text.
Do not count empty words as words.
>>> average_sentence_length('A pearl! Pearl! Lustrous pearl! \
Rare. What a nice find.')
2.0
'''
sentences = get_sentences(text) #1
total = 0
for sentence in sentences: #2
words = sentence.split() #3
for word in words: #4
if word != '':
total += 1
return total / len(sentences) #5
Inspect the complete Python implementation, including sentence retrieval, word counting, empty-word handling, and averaging. section 11.5.7
