Home > OS >  How to count total words in a text file without using rstrip() in Python?
How to count total words in a text file without using rstrip() in Python?

Time:06-02

Good day!

I have the following snippets:

words_count = 0
lines_count = 0
line_max = None

file = open("alice.txt", "r")

for line in file:
    line = line.rstrip("\n")
    words = line.split()
    words_count  = len(words)
    if line_max == None or len(words) > len(line_max.split()):
        line_max = line
    lines.append(line)

file.close()

This is using rstrip method to get rid of the white spaces in the file, but my exam unit do not allow the method rstrip since it was not introduced. My question is: Is there any other way to get the same result of Total number of words: 26466 without using the rstrip?

Thank you guys!

CodePudding user response:

Interestingly, this works for me without using str.rstrip:

import requests

wc = 0
content = requests.get('https://files.catbox.moe/dz39pw.txt').text

for line in content.split('\n'):
    # line = line.rstrip("\n")
    words = line.split()
    wc  = len(words)

assert wc == 26466

Note that a one-liner way of doing that in Python could be:

wc = sum(len(line.split()) for line in content.split('\n'))
  • Related