NLTK (Natural Language Toolkit) 是一个强大的Python库,用于处理自然语言文本。它提供了丰富的文本处理工具和算法,可以帮助您进行文本分析、文本挖掘、词性标注、命名实体识别等。

安装 NLTK

首先,您需要安装 NLTK 库。可以通过以下命令安装:

pip install nltk

常用功能

1. 词频统计

NLTK 提供了 FreqDist 类,可以用来统计文本中单词的频率。

from nltk.probability import FreqDist

text = "This is a sample text. This text is just a sample."
fdist = FreqDist(text.split())
print(fdist.most_common())

2. 词性标注

NLTK 的 pos_tag 函数可以用来对文本进行词性标注。

from nltk import pos_tag

text = "NLTK is a leading platform for building Python programs to work with human language data."
tokens = word_tokenize(text)
tagged = pos_tag(tokens)
print(tagged)

3. 命名实体识别

NLTK 的 ne_chunk 函数可以用来进行命名实体识别。

from nltk import ne_chunk

text = "Apple Inc. is an American multinational technology company headquartered in Cupertino, California."
tokens = word_tokenize(text)
tree = ne_chunk(pos_tag(tokens))
print(tree)

扩展阅读

更多关于 NLTK 的信息和教程,请访问我们的 NLTK 教程页面

NLTK Logo