python基于百度,哈工大等停用表进行的中文分词

python 复制代码
import os
import pandas as pd
import jieba


# 加载停用词
def load_stopwords(filenames):
    stopwords = set()
    for filename in filenames:
        with open(filename, 'r', encoding='utf-8') as f:
            for line in f:
                stopwords.add(line.strip())
    return stopwords


# 中文分词并去除停用词
def segment_and_remove_stopwords(text, stopwords):
    words = jieba.cut(text)
    filtered_words = [word for word in words if word not in stopwords and len(word) > 1]
    return ' '.join(filtered_words)


# 处理评论数据
def process_comments(df, comment_column, stopwords):
    df['connected_words'] = df[comment_column].apply(lambda x: segment_and_remove_stopwords(x, stopwords))
    return df


# 主函数
def main(input_file_path, output_file_path, comment_column, stopwords_files=[]):
    # 加载停用词
    stopwords = load_stopwords(stopwords_files)

    # 读取CSV文件
    df = pd.read_csv(input_file_path, encoding='utf-8')

    # 处理评论数据
    processed_df = process_comments(df, comment_column, stopwords)

    # 保存处理后的数据到新的CSV文件
    processed_df.to_csv(output_file_path, index=False, encoding='utf-8-sig')

    print(f"数据预处理完成,已保存到 {output_file_path}")



if __name__ == '__main__':
    input_file_path = r"D:\pycharm\爬虫案列\24.汽车之家\_0_10.csv"  # 你的CSV文件路径
    output_file_path = 'comments_processed.csv'  # 输出文件的路径
    comment_column = '空间'  # 假设评论数据在'comment'列中

    # 停用词文件列表,确保这些文件在你的工作目录中
    stopwords_files = [
        r"stopwords-master\baidu_stopwords.txt",
        r"stopwords-master\cn_stopwords.txt",
        r"stopwords-master\hit_stopwords.txt",
        r"stopwords-master\scu_stopwords.txt",
        # ... 其他停用词文件
    ]

    # 确保所有停用词文件都存在
    for filename in stopwords_files:
        if not os.path.exists(filename):
            print(f"Stopwords file {filename} not found.")
            exit(1)

            # 调用主函数处理评论数据
    main(input_file_path, output_file_path, comment_column, stopwords_files)

停用词表可以去看一下博主的上传的资源 , 可以免费获取的

相关推荐
喵手2 分钟前
Python爬虫实战:采集菜谱网站的“分类/列表页”(例如“家常菜”或“烘焙”频道)数据,构建高可用的美食菜谱数据采集流水线(附CSV导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·采集菜谱网站数据·家常菜或烘焙频道·构建高可用食谱数据采集系统
喵手3 分钟前
Python爬虫实战:硬核解析 Google Chrome 官方更新日志(正则+文本清洗篇)(附 CSV 导出)!
爬虫·python·爬虫实战·零基础python爬虫教学·csv导出·监控谷歌版本发布历史·获取稳定版更新日志
小邓睡不饱耶6 分钟前
实战|W餐饮平台智能化菜品推荐方案(含Spark实操+算法选型+完整流程)
python·ai·ai编程·ai写作
草莓熊Lotso8 分钟前
Qt 主窗口核心组件实战:菜单栏、工具栏、状态栏、浮动窗口全攻略
运维·开发语言·人工智能·python·qt·ui
aiguangyuan12 分钟前
基于BiLSTM-CRF的命名实体识别模型:原理剖析与实现详解
人工智能·python·nlp
禹凕17 分钟前
Python编程——进阶知识(MYSQL引导入门)
开发语言·python·mysql
阿钱真强道19 分钟前
13 JetLinks MQTT:网关设备与网关子设备 - 温控设备场景
python·网络协议·harmonyos
我的xiaodoujiao22 分钟前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 47--设置Selenium以无头模式运行代码
python·学习·selenium·测试工具·pytest
寻星探路6 小时前
【深度长文】万字攻克网络原理:从 HTTP 报文解构到 HTTPS 终极加密逻辑
java·开发语言·网络·python·http·ai·https
ValhallaCoder9 小时前
hot100-二叉树I
数据结构·python·算法·二叉树