0

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!

4
  • 1
    python wordcount.py < your-text-file.txt
    – Ashalynd
    Nov 9, 2015 at 19:58
  • 1
    is there a reason not to use wc utility?
    – jfs
    Nov 9, 2015 at 19:59
  • thanks, @Ashalynd. Well wc utility is just too easy Sebastian =D
    – aznjonn
    Nov 9, 2015 at 20:05
  • Like @J.F.Sebastian says, why not simply use wc -l your-text-file.txt?
    – Hexatonic
    Mar 17, 2016 at 14:58

2 Answers 2

2

sys.stdin.read() reads data from the console. Just run the python program and type whatever you want. When you're done press Ctrl + D.

0
1

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

1
  • 1
    python wordcount.py <somefile.txt
    – jfs
    Nov 9, 2015 at 19:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.