分词、去停用词

本文探讨了自然语言处理中的关键步骤——分词和去停用词操作,旨在提高文本分析的准确性。

分词、去停用词

#https://github.com/xgli/jieba

import os
import jieba

# 未分词语料库路径
corpus_path =r' '
# 分词后语料库路径
seg_path = r' '
# 停用词路径
stop_list_Path = r' '

def stopwordsList(stop_list_Path):
    f = open(stop_list_Path,'r',encoding='utf-8')
    stopwords = [line.strip() for line in f.readlines()]
    return stopwords

def readfile(filepath):
    f = open(filepath,'r',encoding='gb2312',errors='ignore')
    content = f.read()
    # read()返回的是字符串,读全文本的内容。readline()返回一行,是字符串类型。readlines()读取所有行,保存在列表中
    f.close()
    return content
    # 这里返回整个文本,以便后续进行分词
    
def savefile(seg_path,content):
    f = open(seg_path,'w',encoding='utf-8')
    f.write(content)
    f.close()

def tikenizer_and_removeStoplist(corpus_path,stop_list_Path):
    cate_dir = os.listdir(corpus_path) # 获取子类别目录
    for cate in cate_dir:
        cate_complete_dir = corpus_path+'\\'+cate+"\\" # 获取子类别的完整路径
        seg_cate_complete_dir = seg_path + '\\' + cate + "\\"
        if not os.path.exi
当然可以,jieba 分词是一个非常流行的中文分词工具,在处理自然语言任务时,停用词是非常重要的一步。下面我会为你提供一段简单的 Python 代码示例,并解释如何通过 jieba 进行分词停用词。 ### 步骤说明: 1. **安装必要的库**:首先需要确保已经安装了 `jieba` 库。如果还没有安装的话,可以通过 pip 安装: ```bash pip install jieba ``` 2. **加载文本数据**:准备你需要进行分词停用词操作的文本内容。 3. **创建停用词列表**:通常会有一个包含常见无意义词汇(如“的”、“是”等)的文件作为停用词表,将其读入程序中以便后续过滤使用。 4. **利用 jieba 对句子进行分词**:对输入文本按词语切分,默认采用精确模式即可满足大多数需求。 5. **遍历分词结果并与停用词对比**:将不属于停用词集合内的有效词语保存下来形成新的干净文本序列。 6. 输出最终的结果 下面是具体的代码实现: ```python import jieba def load_stopwords(file_path): """从给定路径加载停用词""" with open(file_path, 'r', encoding='utf-8') as f: stopwords = set([line.strip() for line in f]) return stopwords def remove_stopwords(text, stop_words): """移除text中的stopword""" seg_result = list(jieba.cut(text)) # 使用结巴分词器进行分词 cleaned_tokens = [token for token in seg_result if token not in stop_words and len(token)>0] return " ".join(cleaned_tokens) # 示例用法 if __name__ == "__main__": input_text = "这是一个用于测试JIEBA分词功能的小例子" stop_file = './data/stopwords.txt' # 加载停用词 my_stopwords = load_stopwords(stop_file) result = remove_stopwords(input_text, my_stopwords) print("原始文本:", input_text) print("停用词后的文本:", result) ``` 在这个例子中,我们假设你已经有了一个名为 `stopwords.txt` 的停用词文档位于当前目录下的 data 文件夹里;如果没有现成的数据集,也可以很容易在网上找到免费资源下载合适的停用词表格。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值