Python Data Science 简明教程

Python - Word Tokenization

单词标记化是对大量文本进行单词切分的过程。在自然语言处理任务中,这是必需的,其中每个单词都需要被获取,并接受进一步的分析,例如对其进行分类并计算其特定情感等。自然语言工具包 (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']

Tokenizing Sentences

正如对单词进行标记化一样,我们还可以对段落中的句子进行标记化。我们使用 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.']