繁体   English   中英

您好,我是python新手,在将文件作为输入时遇到困难。 有人可以帮我吗?

[英]Hello, I am new to python and I am having difficulties on having a file as an input. Can somebody help me please?

def main():
    lines = 0
    words = 0
    chars = 0
    print("This program will count the number of lines, words, and characters in a file.")
    with open(filename, 'r') as fileObject:
        for l in fileObject:
            wordsfind = l.split()
            lines += 1
            words += len(wordsFind)
            chars += len(l)
        print("The file thoreau.txt has: ")
        print("Lines ==>           ", lines)
        print("Words ==>          ", words)
        print("Characters ==>    ", chars)

main()

如何将文件作为输入,可以选择要计数的文件?

最简单的方法是:

fileName = sys.argv[1]

然后您可以像这样调用脚本:

python myscript.py myfile.txt

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM