Wordcount similar to Unix WC (Python)

bumsfeld 1 Tallied Votes 3K Views Share

Question of wordcount program similar to Unix wc came up in the forum and I worked on a solution. Program shows number of lines, number of words, number of characters and text file's name. Good learning for commandline, file and string handling.

# wordcount example, similar to Linux wc
# works on Windows XP too   HAB

def wordcount(filename):
    try:
        fin = open(filename, 'r')
        text = fin.read()
        fin.close()
    except IOError:
        print "File %s not found" % filename
        raise SystemExit
    # all characters
    number_of_characters = len(text)
    # assumes lines end with '\n'
    # the last line usually has no '\n' so add 1 to count
    number_of_lines = text.count('\n') + 1
    # assumes words are separated by whitespace
    wordlist = text.split(None)
    number_of_words = len(wordlist)
    print "%d %d %d %s" % (number_of_lines, number_of_words, number_of_characters, filename)

# test wordcount()
if __name__ == '__main__':
    import sys

    # there is a commandline
    if len(sys.argv) > 1:
        # sys.argv[0] is the program filename, slice it off
        for filename in sys.argv[1:]:
            wordcount(filename)
    else:
        print "usage wc textfile1 [textfile2 ...]"
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.