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)

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

相关推荐
MM_MS4 分钟前
Halcon图像点运算、获取直方图、直方图均衡化
图像处理·人工智能·算法·目标检测·计算机视觉·c#·视觉检测
DFT计算杂谈5 分钟前
VASP+PHONOPY+pypolymlpj计算不同温度下声子谱,附批处理脚本
java·前端·数据库·人工智能·python
json{shen:"jing"}24 分钟前
js收官总概述
开发语言·python
双层吉士憨包29 分钟前
Airbnb(爱彼迎)爬虫全流程解析:用 Python 抓取房源数据实战指南
python·ai·网络爬虫
小北方城市网35 分钟前
RabbitMQ 生产级实战:可靠性投递、高并发优化与问题排查
开发语言·分布式·python·缓存·性能优化·rabbitmq·ruby
曲幽36 分钟前
FastAPI部署中间件实战:从CORS到自定义,让你的API更健壮
python·fastapi·web·cors·starlette·middleware·call_next
郝学胜-神的一滴41 分钟前
Python中的bisect模块:优雅处理有序序列的艺术
开发语言·数据结构·python·程序人生·算法
jackylzh1 小时前
PyTorch 2.x 中 `torch.load` 的 `FutureWarning` 与 `weights_only=False` 参数分析
人工智能·pytorch·python
MACKEI1 小时前
服务器流式传输接口问题排查与解决方案
python·nginx·流式