liveBook · Manning

Character count

As explained in The Quick Python Book, Fourth Edition

A character count is the number of characters contained in a file or text.

A character count reports the number of characters in a text file. A small Python program can calculate it alongside line and word counts, much like the UNIX wc utility. section 8.12

""" Reads a file and returns the number of lines, words,
    and characters - similar to the UNIX wc utility
"""
 
# initialize counts
line_count = 0                                              #1
word_count = 0                                              #1
char_count = 0                                              #1
 
# open the file
with  open('word_count.tst') as infile:
    for line in infile:                                     #2
        line_count += 1
        char_count += len(line)
        word_count += len(line.split())
 
# print the answers using the format() method
print("File has {0} lines, {1} words, {2} characters".format(line_count, 
                                               word_count, char_count))

The line-by-line version adds len(line) to a running total. Counting each line as read keeps its newline in the count and avoids loading the whole file at once. section 8.13.2

Newlines change the answer

For the four-line sample file, splitting the entire file with split("\n") and summing the lengths of the resulting strings reports 186 characters. The three separators have been discarded; counting the original lines reports 189. section 8.12 section 8.13.2

Another compact approach is sum(len(line) for line in infile.readlines()), but readlines() holds the file's lines in memory. For files of unknown size, iterate over the file instead. In a command-line version, a -c option can request the character count; with no options, line, word, and character counts can be displayed together. section 8.13.2 section 11.5.2

How The Quick Python Book, Fourth Edition covers it

How deep it goes
Works through len(line), line-by-line accumulation, and a newline-loss bug, while comparing whole-file and streaming approaches.
Examples
Compares 186 reported characters with 189 after accounting for three newlines in a four-line sample file.
What it assumes
Assumes general programming familiarity while demonstrating Python file reading, loops, len(), and string splitting in a small program.
What you can do after
Build it from scratch by accumulating len(line) while reading a file, or expose the count through a -c command-line option.
How it connects
Connects character counting to file iteration, string splitting, line counts, word counts, and command-line arguments.

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.