# This program reads numbers from a file into a list.
def main():
    # Open a file for reading.
    infile = open('text.txt', 'r')
    sentences = infile.readlines() # Read the contents of the file into a list.
    infile.close()                          # Close the file.


    index = 0                               # Convert each element to an int.
    while index < len(sentences):



        print (sentences[index], index) #PRINT EACH ELEMENT
        index += 1

        # Print the contents of the list.

    print (index)


# Call the main function.
main()

Dani AI

Generated

's snippet reads the file into a list (lines), which only equals "sentences" when the file is already one sentence per line. 's idea to count terminal punctuation ('.', '?', '!') is a simple heuristic but fails on common cases (abbreviations like "Mr.", decimals, ellipses, quoted dialogue). is correct to recommend doing the math by hand first. Below are two practical approaches: a minimal per-line average (for one-sentence-per-line files) and a regex-based split that works better on free-form text.

import re

WORD_RE = re.compile(r"[A-Za-z0-9]+(?:[-'][A-Za-z0-9]+)*")

def avg_words_per_line(lines):
    counts = [len(line.strip().split()) for line in lines if line.strip()]
    return sum(counts) / len(counts) if counts else 0.0

def avg_words_by_punct(lines):
    text = " ".join(line.strip() for line in lines)
    sentences = [s.strip() for s in re.split(r'(?<=[.!?])\s+', text) if s.strip()]
    counts = [len(WORD_RE.findall(s)) for s in sentences if WORD_RE.search(s)]
    return sum(counts) / len(counts) if counts else 0.0

if __name__ == "__main__":
    with open("text.txt", "r", encoding="utf-8") as f:
        lines = f.readlines()
    print("avg (per line):", avg_words_per_line(lines))
    print("avg (by punctuation):", avg_words_by_punct(lines))

Notes and troubleshooting: the WORD_RE pattern treats contractions and hyphenated words as single tokens (e.g., "don't", "self-employed"); the re.split approach splits on punctuation followed by whitespace and will still mis-handle abbreviations (e.g., "e.g.", "Dr.") and some ellipses. For higher accuracy on real prose, a trained sentence tokenizer (for example, NLTK's Punkt tokenizer nltk.tokenize.sent_tokenize or a spaCy pipeline) is recommended. Common causes of wrong averages include silent empty lines, incorrect file encoding, or input where sentences span multiple lines—these need cleaning or joining before counting. Finally, validating results on a small hand-counted sample, as suggested, helps confirm the chosen method matches the intended definition of "sentence."

Recommended Answers

All 2 Replies

Take a page containing a list of sentences, like (take only the first 5 sentences). Then with a calculator, compute the average number of words per sentence by hand and note carefully everything you do. This should give you a working algorithm. Write pseudo code, then python code.

Assume the sentences end with '.' or '?' or '!' so count these characters and divide the total words by the number of these characters.

commented: interesting idea +13
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.