liveBook · Manning

Average_sentence_length

As explained in Learn AI-Assisted Python Programming, Second Edition

average_sentence_length is a book-specific Python function that calculates the average number of words per sentence in text.

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

How Learn AI-Assisted Python Programming, Second Edition covers it

How deep it goes
Explains the counting implementation and sentence-boundary limitation, but stops short of robust natural-language sentence detection.
Examples
Uses a doctest with five short sentences and an abbreviation example involving “Mrs.”.
What it assumes
Assumes a text string and teaches sentence extraction through punctuation before performing word counting.
What you can do after
Apply it via Python to measure average words per sentence in a text.
How it connects
Connects sentence splitting, string split, clean_word, and authorship identification.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn AI-Assisted Python Programming, Second Edition. The section links point to the parts of the book it draws on.