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']
廣告

© . All rights reserved.