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!
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'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.