Python - 字数统计脚本

Python - Word Count script

下面是我在网上找到的 Python 字数统计脚本,但我很难理解你会如何 运行 这个。我是否需要在 Python 中创建一个文件并在 Python 中打开它才能使该程序运行 运行?

#!/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))

感谢您的帮助!

sys.stdin.read() 从控制台读取数据。只需 运行 python 程序并输入您想要的任何内容。完成后按 Ctrl + D.

sys.stdin.read() 行告诉我它期望从标准输入接收输入,因此您可以像这样使用它:

type somefile.txt | python wordcount.py

或 运行 python wordcount.py 并在控制台中输入以 ctrl-d

结尾的内容