Wordcount similar to Unix WC (Python) UserPageVisits:2048 active 80 80 DaniWeb 561 60 2006-02-25T23:24:00+00:00 https://www.daniweb.com/programming/software-development/code/216702/wordcount-similar-to-unix-wc-python

Wordcount similar to Unix WC (Python)


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.

About the Author


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

def wordcount(filename):
        fin = open(filename, 'r')
        text = fin.read()
    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:]:
        print "usage wc textfile1 [textfile2 ...]"
Be a part of the DaniWeb community

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