1. 程式人生 > >Python資料操作—單詞標記化

Python資料操作—單詞標記化

單詞標記是將大量文字樣本分解為單詞的過程。 這是自然語言處理任務中的一項要求,每個單詞需要被捕獲並進行進一步的分析,如對特定情感進行分類和計數等。自然語言工具包(NLTK)是用於實現這一目的的庫。 在繼續使用python程式進行字詞標記之前,先安裝NLTK。
命令:
conda install -c anaconda nltk
nltk.download('punkt')

當出現下面這種,表示安裝nltk成功,
這裡寫圖片描述

下面就可以使用word_tokenize方法將段落拆分為單個單詞,程式碼:

#拆分單詞
import nltk
word_data = "It originated from the idea that there are readers who prefer learning new skills from the comforts of their drawing rooms"
nltk_tokens = nltk.word_tokenize(word_data) print (nltk_tokens)

結果:

['It', 'originated', 'from', 'the', 'idea', 'that', 'there', 'are', 'readers', 
'who', 'prefer', 'learning', 'new', 'skills', 'from', 'the',
'comforts', 'of', 'their', 'drawing', 'rooms']

標記句子:使用send_tokenize方法來實現。
例:

#拆分句子
import nltk sentence_data = "Sun rises in the east. Sun sets in the west." nltk_tokens = nltk.sent_tokenize(sentence_data) print (nltk_tokens)

結果:

['Sun rises in the east.', 'Sun sets in the west.']