Python – 分词

Python – 分词

在Python中,分词基本上是将较大的文本分割成较小的行、单词或甚至是用于非英语语言的单词。nltk模块内置的各种分词函数可以像下面的程序一样在程序中使用。

行分词

在下面的示例中,我们使用函数sent_tokenize将给定的文本分成不同的行。

import nltk
sentence_data = "The First sentence is about Python. The Second: about Django. You can learn Python,Django and Data Ananlysis here. "
nltk_tokens = nltk.sent_tokenize(sentence_data)
print(nltk_tokens)

当我们运行上述程序时,我们得到以下输出-

['The First sentence is about Python.', 'The Second: about Django.', 'You can learn Python,Django and Data Ananlysis here.']

非英语分词

在下面的示例中,我们对德语文本进行分词。

import nltk

german_tokenizer = nltk.data.load('tokenizers/punkt/german.pickle')
german_tokens=german_tokenizer.tokenize('Wie geht es Ihnen?  Gut, danke.')
print(german_tokens)

当我们运行上述程序时,我们得到以下输出-

['Wie geht es Ihnen?', 'Gut, danke.']

单词分词

我们使用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']

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程