- Python - 文字處理
- Python - 文字處理簡介
- Python - 文字處理環境
- Python - 字串不變性
- Python - 排序行
- Python - 重新格式化段落
- Python - 統計段落中的令牌
- Python - 二進位制 ASCII 轉換
- Python - 字串作為檔案
- Python - 向後檔案讀取
- Python - 過濾重複的單詞
- Python - 從文字中提取電子郵件
- Python - 從文字中提取 URL
- Python - 漂亮列印
- Python - 文字處理狀態機
- Python - 大寫和小寫並翻譯
- Python - 詞形還原
- Python - 刪除停用詞
- Python - 同義詞和反義詞
- Python - 文字翻譯
- Python - 詞語替換
- Python - 拼寫檢查
- Python - WordNet 介面
- Python - 語料庫訪問
- Python - 標註詞語
- Python - 滿足條件的塊內容和不滿足條件的塊內容
- Python - 塊分類
- Python - 文字分類
- Python - 雙詞
- Python - 處理 PDF
- Python - 處理 Word 文件
- Python - 讀取 RSS 訂閱
- Python - 情感分析
- Python - 搜尋和匹配
- Python - 文字歸併
- Python - 文字換行
- Python - 頻率分佈
- Python - 文字摘要
- Python - 詞幹演算法
- Python - 限定搜尋
Python - 頻率分佈
文字處理時,通常需要計算某個單詞在文字中出現的頻率。這可以透過應用 word_tokenize() 函式並將其結果追加到列表中來實現,以統計單詞,如下面的程式所示。
from nltk.tokenize import word_tokenize
from nltk.corpus import gutenberg
sample = gutenberg.raw("blake-poems.txt")
token = word_tokenize(sample)
wlist = []
for i in range(50):
wlist.append(token[i])
wordfreq = [wlist.count(w) for w in wlist]
print("Pairs\n" + str(zip(token, wordfreq)))
當我們執行上述程式時,會得到以下輸出 −
[([', 1), (Poems', 1), (by', 1), (William', 1), (Blake', 1), (1789', 1), (]', 1), (SONGS', 2), (OF', 3), (INNOCENCE', 2), (AND', 1), (OF', 3), (EXPERIENCE', 1), (and', 1), (THE', 1), (BOOK', 1), (of', 2), (THEL', 1), (SONGS', 2), (OF', 3), (INNOCENCE', 2), (INTRODUCTION', 1), (Piping', 2), (down', 1), (the', 1), (valleys', 1), (wild', 1), (,', 3), (Piping', 2), (songs', 1), (of', 2), (pleasant', 1), (glee', 1), (,', 3), (On', 1), (a', 2), (cloud', 1), (I', 1), (saw', 1), (a', 2), (child', 1), (,', 3), (And', 1), (he', 1), (laughing', 1), (said', 1), (to', 1), (me', 1), (:', 1), (``', 1)]
條件頻率分佈
當我們想計算滿足特定條件的文字中出現的單詞時,可以使用條件頻率分佈。
import nltk
#from nltk.tokenize import word_tokenize
from nltk.corpus import brown
cfd = nltk.ConditionalFreqDist(
(genre, word)
for genre in brown.categories()
for word in brown.words(categories=genre))
categories = ['hobbies', 'romance','humor']
searchwords = [ 'may', 'might', 'must', 'will']
cfd.tabulate(conditions=categories, samples=searchwords)
當我們執行上述程式時,會得到以下輸出 −
may might must will hobbies 131 22 83 264 romance 11 51 45 43 humor 8 8 9 13
廣告