Find the number of characters in a file using Python

后端 未结 16 1438
春和景丽
春和景丽 2021-02-07 00:34

Here is the question:

I have a file with these words:

hey how are you
I am fine and you
Yes I am fine

And it is asked to find the numbe

16条回答
  •  梦谈多话
    2021-02-07 01:08

    Sum up the length of all words in a line:

    characters += sum(len(word) for word in wordslist)
    

    The whole program:

    with open('my_words.txt') as infile:
        lines=0
        words=0
        characters=0
        for line in infile:
            wordslist=line.split()
            lines=lines+1
            words=words+len(wordslist)
            characters += sum(len(word) for word in wordslist)
    print(lines)
    print(words)
    print(characters)
    

    Output:

    3
    13
    35
    

    This:

    (len(word) for word in wordslist)
    

    is a generator expression. It is essentially a loop in one line that produces the length of each word. We feed these lengths directly to sum:

    sum(len(word) for word in wordslist)
    

    Improved version

    This version takes advantage of enumerate, so you save two lines of code, while keeping the readability:

    with open('my_words.txt') as infile:
        words = 0
        characters = 0
        for lineno, line in enumerate(infile, 1):
            wordslist = line.split()
            words += len(wordslist)
            characters += sum(len(word) for word in wordslist)
    
    print(lineno)
    print(words)
    print(characters)
    

    This line:

    with open('my_words.txt') as infile:
    

    opens the file with the promise to close it as soon as you leave indentation. It is always good practice to close file after your are done using it.

提交回复
热议问题