簡體   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