Python程式:統計文字檔案中的單詞數
在處理文字處理和分析任務時,通常需要統計文字檔案中的單詞數。目標是確定檔案中存在的單詞總數。Python 提供了幾個模組和函式,可以高效有效地執行單詞計數任務。
在本文中,我們將探討使用 Python 程式設計從文字檔案獲取單詞總數的不同方法。
方法
以下是統計文字檔案單詞數的步驟:
開啟文字檔案 - 使用 open() 函式以讀取模式開啟文字檔案。指定檔案路徑作為引數。
讀取檔案內容 - 使用 read() 方法將檔案的全部內容讀取到字串變數中。
將內容分割成單詞 - 將內容字串分割成單詞列表。我們可以使用 split() 方法或正則表示式模式 (\b\w+\b) 來分割內容。
統計單詞數 - 確定列表中的單詞數。我們可以使用 len() 函式獲取列表的長度。
最後,返回單詞計數。
在本文中,我們將使用以下文字檔案作為輸入。

使用 split() 方法
split() 是一個 Python 字串方法,它根據指定的定界符將字串分割成子字串列表。split() 方法可以使用空格作為預設定界符將字串分割成單詞。
示例
這是一個統計文字檔案單詞數的示例。
def count_words(filename): try: with open(filename, 'r') as file: content = file.read() words = content.split() word_count = len(words) return word_count except FileNotFoundError: print(f"File '{filename}' not found.") return 0 # Provide the path of the text file file_path = 'Example_text_file.txt' # Call the function to count words total_words = count_words(file_path) print("Total number of words in the file: {}".format(total_words))
輸出
File 'Example_text_file.txt' not found. Total number of words in the file: 0
使用 collections 模組
在這種方法中,我們使用 collections 模組中的 Counter 類來統計檔案中每個單詞的出現次數。
Counter 物件提供了一個類似字典的結構,其中每個單詞都是鍵,其對應的值表示文字中出現的次數。然後,我們使用 sum() 函式將所有值相加,以獲得單詞總數。
示例
在這個示例中,我們將使用 collections.Counter() 方法來統計文字檔案中存在的單詞數。
import collections def count_words(filename): try: with open(filename, 'r') as file: word_count = collections.Counter(file.read().split()) return sum(word_count.values()) except FileNotFoundError: print(f"File '{filename}' not found.") return 0 # Provide the path of the text file file_path = 'Example_text_file.txt' # Call the function to count words total_words = count_words(file_path) print("Total number of words in the file: {}".format(total_words))
輸出
File 'Example_text_file.txt' not found. Total number of words in the file: 0
使用正則表示式
在這裡,我們將使用 re 模組中的 re.findall() 函式,使用正則表示式模式從檔案內容中提取所有單詞。模式 \b\w+\b 匹配任何由單詞邊界包圍的一個或多個單詞字元(字母、數字或下劃線)的序列。
findall() 函式返回在內容中找到的所有匹配項的列表。然後,我們確定列表的長度以獲得單詞總數。
示例
這是另一種使用 Python 中的正則表示式統計文字檔案單詞數的方法。
import re def count_words(filename): try: with open(filename, 'r') as file: content = file.read() words = re.findall(r'\b\w+\b', content) word_count = len(words) return word_count except FileNotFoundError: print(f"File '{filename}' not found.") return 0 # Provide the path of the text file file_path = 'Example_text_file.txt' # Call the function to count words total_words = count_words(file_path) print(f"Total number of words in the file: {total_words}")
輸出
File 'Example_text_file.txt' not found. Total number of words in the file: 0
這些是使用 Python 程式設計統計文字檔案單詞數的不同方法。