掌握NLTK:Python自然语言处理库中级教程

在之前的初级教程中,我们已经了解了NLTK(Natural Language Toolkit)的基本用法,如进行文本分词、词性标注和停用词移除等。在本篇中级教程中,我们将进一步探索NLTK的更多功能,包括词干提取、词形还原、n-gram模型以及词云的绘制。

一、词干提取

词干提取是一种将词语简化为其基本形式或词干的过程。例如,"running"、"runner"和"ran"的词干可能都是"run"。在NLTK中,我们可以使用Porter词干提取器进行词干提取:

python 复制代码
from nltk.stem import PorterStemmer
from nltk.tokenize import word_tokenize

ps = PorterStemmer()

words = ["run", "runner", "running", "ran"]
for w in words:
    print(ps.stem(w))

二、词形还原

与词干提取相似,词形还原也是简化词语的一种方式,但它保留的是词语的词形,而不仅仅是词干。在NLTK中,我们可以使用WordNet词形还原器进行词形还原:

python 复制代码
from nltk.stem import WordNetLemmatizer

lemmatizer = WordNetLemmatizer()

print(lemmatizer.lemmatize("running"))
print(lemmatizer.lemmatize("ran", pos='v'))

三、n-gram模型

n-gram是一种语言模型,用于预测下一个词的可能性。n-gram模型基于统计的方法,考虑前n-1个词来预测下一个词。在NLTK中,我们可以使用ngrams函数来生成n-gram:

python 复制代码
from nltk import ngrams
from nltk.tokenize import word_tokenize

sentence = "I love to play football"
n = 2
grams = ngrams(word_tokenize(sentence), n)
for gram in grams:
    print(gram)

四、绘制词云

词云是一种可视化技术,用于表示文本数据中词的频率。在NLTK中,虽然没有直接提供绘制词云的函数,但我们可以结合wordcloud库来创建词云:

python 复制代码
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from wordcloud import WordCloud
import matplotlib.pyplot as plt

text = "NLTK is a leading platform for building Python programs to work with human language data."
stop_words = set(stopwords.words('english'))

words = word_tokenize(text)
words = [word for word in words if word not in stop_words]

wordcloud = WordCloud().generate(' '.join(words))

plt.imshow(wordcloud)
plt.axis("off")
plt.show()

以上,我们介绍了NLTK库中的一些中级功能,包括词干提取、词形还原、n-gram模型和词云的绘制等。然而,NLTK还有更多高级的功能和特性,如情感分析、语义角色标注等,值得我们进一步探索和学习。

相关推荐
胡耀超几秒前
AI出事后,怎么查?——读《AI Forensics》
人工智能·python·数字取证·ai取证·
星栈7 分钟前
我以为 TS7.0 只是换个版本号,结果编译快了 9 倍,也踩了 5 个坑
后端·typescript·node.js
梦想三三13 分钟前
Python从零实现AI Agent电商客服(Qwen/Ollama+SQLite源码解析)
人工智能·python·sqlite
Csvn16 分钟前
📊 SQL 入门 Day 15:日期与字符串函数 — SQL 中的数据处理瑞士军刀
后端·sql
鹿鹿学长16 分钟前
国赛工业应用数学题:从31省规上工业数据到生产排程,四类高频赛题的破题打法
python·自动化
用户842981424181019 分钟前
JS代码压缩实测:可减小体积、提高执行效率!
前端·javascript·后端
笨鸟先飞,勤能补拙21 分钟前
密码学深度指南 — SecOps 工程师实战手册
人工智能·vscode·python·安全·github·密码学·visual studio
进击的丸子23 分钟前
虹软人脸SDK 调用常见问题和最佳实践指南
后端
淼澄研学24 分钟前
PyTorch核心实操:从张量计算到混合精度训练的5个关键步骤
人工智能·pytorch·python