Python單詞標記化


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

conda install -c anaconda 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.']