要使用jieba库的停用词功能,你需要先导入jieba库和一个包含停用词的文件。下面是一个简单的示例代码:

import jieba

# 导入停用词文件
stopwords_file = 'stopwords.txt'

# 加载停用词表
def load_stopwords(file):
    stopwords = []
    with open(file, 'r', encoding='utf-8') as f:
        for line in f.readlines():
            stopwords.append(line.strip())
    return stopwords

stopwords = load_stopwords(stopwords_file)

# 分词并去除停用词
def segment(text):
    seg_list = jieba.cut(text)
    seg_list = [word for word in seg_list if word not in stopwords]
    return seg_list

# 示例
text = '我喜欢使用jieba库进行中文分词。'
seg_list = segment(text)
print(seg_list)

在上面的示例中,你需要创建一个名为stopwords.txt的文本文件,其中包含一行一个停用词。然后,使用load_stopwords函数加载停用词表,并在segment函数中使用jieba库进行分词,并过滤掉停用词。最后,你可以调用segment函数来对文本进行分词并打印结果。

请注意,jieba.cut函数返回的是一个生成器对象,你可以使用list函数来将其转换为列表对象。


原文地址: https://www.cveoy.top/t/topic/qxUL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录