Search code examples
pythonwc

Python - Word Count script


Down below is Python word count script that I found online, I am having difficulty understanding how you would run this though. Would I need to create a file and open it in Python before running this program for it to work?

#!/usr/bin/env python

import sys

if __name__ == '__main__':

    data = sys.stdin.read()
    chars = len(data)
    words = len(data.split())
    lines = len(data.split('\n'))

    print ("{0}   {1}   {2}".format(lines, words, chars))

Thanks for any help!


Solution

  • The sys.stdin.read() line tells me that it is expecting to receive the input from the standard input so you can use it something like:

    type somefile.txt | python wordcount.py
    

    or run python wordcount.py and type into the console ending with ctrl-d