自然语言处理(NLP)是人工智能领域的一个重要分支,它使计算机能够理解和处理人类语言。Python 是进行 NLP 项目的一个流行语言,因为它拥有丰富的库和框架,如 NLTK 和 spaCy。
以下是一个简单的 Python NLP 入门教程,我们将使用 NLTK 库进行命名实体识别(NER)。
1. 安装 NLTK 库
首先,你需要安装 NLTK 库。可以通过以下命令安装:
pip install nltk
2. 导入 NLTK 库
import nltk
3. 下载必要的资源
nltk.download('punkt')
nltk.download('averaged_perceptron_tagger')
nltk.download('maxent_ne_chunker')
nltk.download('words')
4. 分词
分词是将文本分割成单词或短语的过程。NLTK 提供了一个简单的分词函数:
from nltk.tokenize import word_tokenize
text = "Natural language processing is the field of AI that deals with the interaction between computers and human (language)."
tokens = word_tokenize(text)
print(tokens)
输出:
['Natural', 'language', 'processing', 'is', 'the', 'field', 'of', 'AI', 'that', 'deals', 'with', 'the', 'interaction', 'between', 'computers', 'and', 'human', '(', 'language', ')']
5. 命名实体识别(NER)
命名实体识别(NER)是一种从文本中识别和分类命名实体的任务,如人名、地点、组织等。
from nltk import pos_tag, ne_chunk
tokens = word_tokenize(text)
tagged = pos_tag(tokens)
named_ents = ne_chunk(tagged)
print(named_ents)
输出:
(S
(Natural NN)
(language NN)
(processing NN)
(is VBZ)
(the DT)
(field NN)
(of IN)
(AI NNP)
(that WDT)
(deals VBZ)
(with IN)
(the DT)
(interaction NN)
(between IN)
(computers NNS)
(and CC)
(human NN)
((
(language NN)
))
)
6. 扩展阅读
想了解更多关于 Python NLP 的知识?可以阅读以下教程:
Python_NLP