import nltk
from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
# 下载必要的资源
nltk.download('punkt')
nltk.download('stopwords')
# 示例文本
text = "This is an example sentence demonstrating the use of NLTK in Python."
# 分词
tokens = word_tokenize(text)
print("分词结果:", tokens)
# 去除停用词
stop_words = set(stopwords.words('english'))
filtered_sentence = [word for word in tokens if word.lower() not in stop_words]
print("去除停用词后的结果:", filtered_sentence)
nltk
及其相关子模块,包括 stopwords
和 word_tokenize
。nltk.download()
下载了分词和停用词所需的资源。word_tokenize
对句子进行分词,并将结果存储在 tokens
列表中。stopwords.words('english')
获取英文停用词集合,并过滤掉这些停用词,得到最终的 filtered_sentence
。希望这段代码能帮助你理解如何使用 nltk
进行基本的自然语言处理任务。
上一篇:python中字符串怎么比较大小
下一篇:python随机数怎么生成
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站