簡體   English   中英

計算python3中文本文件的單詞

[英]count words of text file in python3

我正在學習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 我從文本文件中獲取拆分后的文本,但是當我嘗試打印長度時,我只是得到了最后一個單詞的長度。

您需要初始化wordCount = 0 ,然后在for loop每次迭代時都需要添加到wordCount中。 像這樣:

wordCount = 0
for line in hand:
    lin = line.rstrip()
    wds = lin.split()
    print(wds)
    wordCount += len(wds)
print(wordCount)

有四件事要做:

  • 打開一個文件
  • 從文件中讀取行
  • 從行中讀單詞
  • 打印字數

因此,只需按該順序執行;)

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)}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM