繁体   English   中英

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

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

再会!

我有以下片段:

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()

这是使用 rstrip 方法去除文件中的空格,但我的考试单元不允许使用 rstrip 方法,因为它没有被引入。 我的问题是:有没有其他方法可以在不使用 rstrip 的情况下获得与Total number of words: 26466相同的结果?

感谢你们!

有趣的是,这对我有用,而无需使用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

请注意,在 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