1. 程式人生 > >如何利用python統計英文文章詞頻

如何利用python統計英文文章詞頻

應用介紹:
統計英文文章詞頻是很常見的需求,本文利用python實現。
思路分析:
1、把英文文章的每個單詞放到列表裡,並統計列表長度;
2、遍歷列表,對每個單詞出現的次數進行統計,並將結果儲存在字典中;
3、利用步驟1中獲得的列表長度,求出每個單詞出現的頻率,並將結果儲存在頻率字典中;
3、以字典鍵值對的“值”為標準,對字典進行排序,輸出結果(也可利用切片輸出頻率最大或最小的特定幾個,因為經過排序sorted()函式處理後,單詞及其頻率資訊已經儲存在元組中,所有元組再組成列表。)
程式碼實現:

fin = open('The_Magic_Skin _Honore_de_Balzac.txt'
) #the txt is up #to you lines=fin.readlines() fin.close() '''transform the article into word list ''' def words_list(): chardigit='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 ' all_lines = '' for line in lines: one_line='' for ch in line: if
ch in chardigit: one_line = one_line + ch all_lines = all_lines + one_line return all_lines.split() '''calculate the total number of article list s is the article list ''' def total_num(s): return len(s) '''calculate the occurrence times of every word t is the article list '''
def word_dic(t): fre_dic = dict() for i in range(len(t)): fre_dic[t[i]] = fre_dic.get(t[i],0) + 1 return fre_dic '''calculate the occurrence times of every word w is dictionary of the occurrence times of every word ''' def word_fre(w): for key in w: w[key] = w[key] / total return w '''sort the dictionary v is the frequency of words ''' def word_sort(v): sort_dic = sorted(v.items(), key = lambda e:e[1]) return sort_dic '''This is entrance of functions output is the ten words with the largest frequency ''' total = total_num(words_list()) print(word_sort(word_fre(word_dic(words_list())))[-10:])