再會!
我有以下片段:
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 方法,因為它沒有被引入。我的問題是:有沒有其他方法可以在Total number of words: 26466不使用 rstrip 的情況下獲得相同的結果?
感謝你們!
uj5u.com熱心網友回復:
有趣的是,這對我有用,無需使用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'))
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/485534.html
標籤:Python python-3.x
