開始使用免費開始

詞頻分析

恭喜你!你剛加入 PyBooks。PyBooks 正在開發書籍推薦系統,他們想從文字中找出模式與趨勢,以改進推薦效果。

首先,你需要了解給定文本中的詞語出現頻率,並移除任何罕見詞。

請注意,真實世界的典型資料集通常會比這個範例更大。

本練習屬於課程

Deep Learning for Text with PyTorch

檢視課程

練習說明

  • torchtext 匯入 get_tokenizer,並從 nltk 函式庫匯入 FreqDist
  • 以英文初始化 tokenizer,並將給定的 text 進行斷詞。
  • 計算 tokens 的詞頻分佈,並使用串列推導式移除罕見詞。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# Import the necessary functions
from torchtext.data.utils import ____
from nltk.probability import ____

text = "In the city of Dataville, a data analyst named Alex explores hidden insights within vast data. With determination, Alex uncovers patterns, cleanses the data, and unlocks innovation. Join this adventure to unleash the power of data-driven decisions."

# Initialize the tokenizer and tokenize the text
tokenizer = ____("basic_english")
tokens = tokenizer(____)

threshold = 1
# Remove rare words and print common tokens
freq_dist = ____(____)
common_tokens = [token for token in tokens if ____[token] > ____]
print(common_tokens)
編輯並執行程式碼