简体   繁体   English

如何在不使用 Python 中的 rstrip() 的情况下计算文本文件中的总字数?

[英]How to count total words in a text file without using rstrip() in Python?

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.这是使用 rstrip 方法去除文件中的空格,但我的考试单元不允许使用 rstrip 方法,因为它没有被引入。 My question is: Is there any other way to get the same result of Total number of words: 26466 without using the rstrip?我的问题是:有没有其他方法可以在不使用 rstrip 的情况下获得与Total number of words: 26466相同的结果?

Thank you guys!感谢你们!

Interestingly, this works for me without using str.rstrip :有趣的是,这对我有用,而无需使用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:请注意,在 Python 中这样做的一种单行方式可能是:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM