Python 簡易詞頻統計

2021-08-28 08:07:58 字數 952 閱讀 3721

做乙個詞頻統計程式,該程式具有以下功能

基本要求:

(1)可匯入任意英文文本文

(2)統計該英文檔案中單詞數和各單詞出現的頻率(次數),並能將單詞按字典順序輸出。

(3)將單詞及頻率寫入檔案。

def read_file(file):

f= open(file,'r')

word = f.read()#讀取檔案

word = word.split()#生成列表

word =sorted(word) # 排序

return word

def result(word):

sum = 0 #定義乙個記錄總詞數的變數

for i in word:

count = word.count(i)#統計每個單詞的個數

sum += count #統計該文章的總詞數

for t in range(count-1):

word.remove(i) #清除統計後的單詞

if ' ' in word:

word.pop(' ') # 刪除空格

f=open('c:\\users\\administrator\\desktop\\out.txt','a')

w ='單詞 '+i+' \t'+'出現次數 '+str(count)+'\n'

f.write(w)#將資料寫入文件

print('本文章共有單詞'+str(sum)+'個')

word= read_file('c:\\users\\administrator\\desktop\\in.txt')

def main(): #定義乙個主函式

result(word)

if __name__ == '__main__':

main()

Python 統計詞頻

calhamletv1.py def gettext txt open hamlet.txt r read txt txt.lower for ch in txt txt.replace ch,將文字中特殊字元替換為空格 return txt hamlettxt gettext words haml...

python 詞頻統計

import re 正規表示式庫 import collections 詞頻統計庫 f open text word frequency statistics.txt article f.read lower 統一轉化成小寫 f.close pattern re.compile t n articl...

python統計詞頻

已知有鍵值對 店名,城市 的鍵值對,我們現在的需求是根據城市來統計店的分布。資料的格式如下 我們希望輸出資料的格式如下所示 所有的資料都是以txt檔案儲存的。from collections import counter from pprint import pprint import os imp...