飲歌長(zhǎng)嘯
2022-05-24 12:45:10
我正在學(xué)習(xí) python,我想創(chuàng)建一個(gè)程序來(lái)計(jì)算文本文件中的單詞總數(shù)。fname = input("Enter file name: ") with open(fname,'r') as hand: for line in hand: lin = line.rstrip() wds = line.split() print(wds) wordCount = len(wds) print(wordCount)我的文本文件的內(nèi)容是: 你好這是我的測(cè)試程序我是 python 新手 謝謝wds當(dāng)我拆分后打印時(shí)。我從文本文件中獲取拆分后的文本,但是當(dāng)我嘗試打印長(zhǎng)度時(shí),我只得到了最后一個(gè)單詞的長(zhǎng)度。
2 回答

一只名叫tom的貓
TA貢獻(xiàn)1906條經(jīng)驗(yàn) 獲得超3個(gè)贊
您需要初始化wordCount = 0,然后在for loop每次迭代時(shí)都需要添加到 wordCount 中。像這樣的東西:
wordCount = 0
for line in hand:
lin = line.rstrip()
wds = lin.split()
print(wds)
wordCount += len(wds)
print(wordCount)

小怪獸愛(ài)吃肉
TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊
有四件事要做:
打開一個(gè)文件
從文件中讀取行
從行中讀取單詞
打印字?jǐn)?shù)
所以,只需按順序執(zhí)行即可;)
with open(fname,'r') as f:
words = [word for line in f
for word in line.strip().split()]
print(f"Number of words: {len(words)}")
添加回答
舉報(bào)
0/150
提交
取消