簡體   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