liveBook · Manning

Word count

As explained in The Quick Python Book, Fourth Edition

A word count is the number of words identified in a text according to a specified word-segmentation rule.

A word count reports how many words a text contains. In a simple Python file counter, each word is a piece returned by line.split(): count those pieces with len(), then add the result for every line. The count therefore depends on the rule used to identify words. section 8.12 section 8.13.2

Count a file line by line

Initialize word_count = 0, then use `with open('word_count.tst') as infile:` and, for each line, run `word_count += len(line.split())`. The sample file produces 30 words; the same program also reports 4 lines and 186 characters. Reading one line at a time avoids keeping the entire file in memory. section 8.13.2 section 8.12

Choose the counting rule to match the task:

  • For a total, add `len(line.split())` across the file. To count only alphabetic pieces, filter the split results with `word.isalpha()` before taking their length. section 8.13.2
  • For counts per distinct word, use each word as a dictionary key and increment its value. Sort the dictionary’s items to find the most and least common words; this is a frequency count, not the single total. section 7.8 section 18.6.2

A command-line counter can report word, line, and character counts together, or select the word count with a `-w` option. Reading all lines first permits a compact `sum(len(line.split()) for line in lines)`, but may be unsuitable for a very large file. section 11.5.2 section 8.13.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through split-based counting, line-by-line accumulation, alphabetic filtering, and dictionary frequencies without defining a universal word boundary.
Examples
Uses a four-line sample reporting 30 words and a cleaned text file ranked by most and least common words.
What it assumes
Assumes general programming familiarity while demonstrating Python file reading, loops, split(), and len() in a small program.
What you can do after
Build it from scratch as a Python file counter, then adapt it for alphabetic-only counts or per-word frequencies.
How it connects
Connects string splitting and file iteration to line counts, character counts, dictionaries, and command-line argument parsing.

Also explained in

Compare how 2 books explain word count →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Quick Python Book, Fourth Edition. The section links point to the parts of the book it draws on.