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.']
广告