Code前端首页关于Code前端联系我们

Python数据科学教程:NLTK单词标记化(自然语言处理任务)

terry 2年前 (2023-09-25) 阅读数 52 #后端开发

单词标记化是将大量文本样本划分为单词的过程。这是自然语言处理任务的要求,其中每个单词都需要被捕获并进一步分析,例如特定情感的分类和计数等。自然语言工具包 (NLTK) 是用于此目的的库。先安装NLTK,然后再继续使用python来标记单词。

conda install -c anaconda nltk
Python

接下来,使用 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)
Python

当我们运行上面的代码时,会产生以下结果。

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

标记句子

您还可以标记段落内的句子,就像单词一样。使用 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)
Python

当我们运行上面的代码时,会生成以下结果。

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

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

热门