Find the number of characters in a file using Python

后端 未结 16 1823
春和景丽
春和景丽 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:04

    A more Pythonic solution than the others:

    with open('foo.txt') as f:
      text = f.read().splitlines() # list of lines
    
    lines = len(text) # length of the list = number of lines
    words = sum(len(line.split()) for line in text) # split each line on spaces, sum up the lengths of the lists of words
    characters = sum(len(line) for line in text) # sum up the length of each line
    
    print(lines)
    print(words)
    print(characters)
    

    The other answers here are manually doing what str.splitlines() does. There's no reason to reinvent the wheel.

提交回复
热议问题