Natural Language Toolkit (NLTK) 是一个强大的Python库,用于处理人类语言数据。以下是一些NLTK的基本示例。
Tokenization
Tokenization 是将文本分解成单词、句子或词汇的过程。NLTK 提供了多种Tokenization 方法。
- 使用
word_tokenize
进行单词分解。 - 使用
sent_tokenize
进行句子分解。
from nltk.tokenize import word_tokenize, sent_tokenize
text = "NLTK is a leading platform for building Python programs to work with human language data."
words = word_tokenize(text)
sentences = sent_tokenize(text)
print(words)
print(sentences)
Part-of-Speech Tagging
Part-of-Speech (POS) Tagging 是为文本中的每个单词分配一个词性标签的过程,如名词、动词等。
from nltk.tokenize import word_tokenize
from nltk import pos_tag
words = word_tokenize(text)
tags = pos_tag(words)
print(tags)
Named Entity Recognition (NER)
Named Entity Recognition 是识别文本中的命名实体,如人名、地点等。
from nltk.tokenize import word_tokenize
from nltk import ne_chunk
words = word_tokenize(text)
tree = ne_chunk(pos_tag(words))
print(tree)
Sentiment Analysis
Sentiment Analysis 是确定文本的情感倾向,如正面、负面或中性。
from nltk.sentiment import SentimentIntensityAnalyzer
sia = SentimentIntensityAnalyzer()
sentiment = sia.polarity_scores(text)
print(sentiment)
NLTK Logo
更多关于NLTK的示例和教程,请访问我们的 NLTK教程页面。