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']

句子標記化

我們還可以像標記化單詞一樣標記化段落中的句子。我們使用sent_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.']
廣告
© . All rights reserved.