- Python - 文字處理
- Python - 文字處理簡介
- Python - 文字處理環境
- Python - 字串不可變性
- Python - 對行排序
- Python - 重新設定段落格式
- Python - 計數段落中的標記
- Python - 二進位制 ASCII 轉換
- Python - 將字串作為檔案
- Python - 向後讀取檔案
- Python - 過濾重複單詞
- Python - 從文字中提取電子郵件
- Python - 從文字中提取網址
- 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 - 過濾重複單詞
很多時候,我們需要分析文字,只需要瞭解該檔案中存在的唯一單詞。因此,我們需要從文字中去除重複單詞。我們需要使用 nltk 中可用的單詞標記化和集合函式,才能實現這一點。
不保留順序
在下面的示例中,我們首先將句子標記為詞語。然後,我們應用 create() 函式,該函式建立一個獨一無二元素的無序集合。結果包含唯一的單詞,不按順序排列。
import nltk word_data = "The Sky is blue also the ocean is blue also Rainbow has a blue colour." # First Word tokenization nltk_tokens = nltk.word_tokenize(word_data) # Applying Set no_order = list(set(nltk_tokens)) print no_order
我們執行上述程式後,會得到以下輸出 −
['blue', 'Rainbow', 'is', 'Sky', 'colour', 'ocean', 'also', 'a', '.', 'The', 'has', 'the']
保留順序
為了在移除重複項後仍然保留句子中單詞的順序,我們讀取單詞並透過附加將其新增到列表中。
import nltk
word_data = "The Sky is blue also the ocean is blue also Rainbow has a blue colour."
# First Word tokenization
nltk_tokens = nltk.word_tokenize(word_data)
ordered_tokens = set()
result = []
for word in nltk_tokens:
if word not in ordered_tokens:
ordered_tokens.add(word)
result.append(word)
print result
我們執行上述程式後,會得到以下輸出 −
['The', 'Sky', 'is', 'blue', 'also', 'the', 'ocean', 'Rainbow', 'has', 'a', 'colour', '.']
廣告