Python Text Processing 简明教程

Python - Tokenization

Line Tokenization

在下面的示例中,我们使用函数 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.']

Non-English Tokenization

在以下示例中,我们将对德语文本进行标记。

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

Word Tokenzitaion

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