我正在學習 python,我想創建一個程序來計算文本文件中的單詞總數。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)我的文本文件的內容是: 你好這是我的測試程序我是 python 新手 謝謝wds當我拆分后打印時。我從文本文件中獲取拆分后的文本,但是當我嘗試打印長度時,我只得到了最后一個單詞的長度。
2 回答

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

小怪獸愛吃肉
TA貢獻1852條經驗 獲得超1個贊
有四件事要做:
打開一個文件
從文件中讀取行
從行中讀取單詞
打印字數
所以,只需按順序執行即可;)
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)}")
添加回答
舉報
0/150
提交
取消