python 文本处理记录

1、移除常见的中文标点符号

python 复制代码
def remove_punc(text):
    # 定义需要去除的中文标点符号的正则表达式
    chinese_punctuation = r'[\u3000-\u303F\uFF01-\uFF0F\uFF1A-\uFF20\uFF3B-\uFF40\uFF5B-\uFF65\u2026]'
    # 使用re.sub函数替换这些标点符号为空字符
    text_without_punctuation = re.sub(chinese_punctuation, '', text)
    return text_without_punctuation

s = "!今天:?、,》。,《》,、天气不错。。。"
ret = remove_punc(s)
print(ret)

2、敏感词过滤

python 复制代码
import pandas as pd
import re

# 构建测试DataFrame数据
dct = {
    "content": [
        "您好,哎,先生您好,我这边是家装平台的客服,给您做个回访。",
        "你好,家长,你翻译给我听啊。",
    ],
    "label": [0, 1],
}
lst = ["先生", "您好", "家长", "天天"]
test_df = pd.DataFrame(dct)

def remove_sensitive_words(text, sensitive_word_list):
    pattern = "|".join(sensitive_word_list)
    return re.sub(pattern, "", text, flags=re.IGNORECASE)

test_df["content_new"] = test_df["content"].apply(remove_sensitive_words, args=(lst,))
# 作用在原始数据上
# test_df["content"] = test_df["content"].apply(remove_sensitive_words, args=(lst,))

test_df.head()

3、jieba分词加载停用词和自定义分词

python 复制代码
import jieba
from collections import Counter


def cut_words(text, stop_path, custom_path=None):
    """
    args:
        text: (str) 待分词的文本
        stop_path: (str) 停用词路径
        custom_path: (str) 自定义分词路径 default: None
    """
    with open(stop_path, "r", encoding="utf-8") as f:
        stopwords = set(f.read().splitlines())
    if custom_path:
        jieba.load_userdict(custom_path)

    words = jieba.lcut(text)

    # 去停用词
    filter_words = [word for word in words if word not in stopwords]
    return "".join(filter_words)

4、文本加载并且保存DataFrame格式

原始文本数据格式如:train.txt

复制代码
体验2D巅峰 倚天屠龙记十大创新概览	8
60年铁树开花形状似玉米芯(组图)	5
同步A股首秀:港股缩量回调	2
中青宝sg现场抓拍 兔子舞热辣表演	8
python 复制代码
from tqdm import tqdm
import pandas as pd

def load_dataset(path):
    contents = []
    labels = []
    with open(path, "r", encoding="UTF-8") as f:
        for line in tqdm(f):
            lin = line.strip()
            if not lin:
                continue
            content, label = lin.split("\t")
            contents.append(content)
            labels.append(label)

    df = pd.DataFrame({"content": contents, "label": labels})
    df.to_csv("./data.csv", index=False)

5、保存自定义文件

python 复制代码
s = "你好,stop_word1,stop_word2"
lst = s.split(",")
# "w" 写模式 "a" 追加模式
with open("b.txt", "w") as file:
    for item in lst:
        file.write(f"{item}\n")

保存结果

复制代码
你好
stop_word1
stop_word2
相关推荐
2766958292几秒前
美团闪购最新版 mtgsig1.2
java·python·node·mtgsig·美团闪购商家端·美团闪购·mtgsig1.1
muspi_merol12 分钟前
Python 启动钩子:.pth 文件的神奇用法✨
python
泽安AI研习社37 分钟前
Cursor用户集体倒戈 !这14招让你榨干Claude Code【建议收藏】
人工智能·python
超浪的晨41 分钟前
Java List 集合详解:从基础到实战,掌握 Java 列表操作全貌
java·开发语言·后端·学习·个人开发
盛夏绽放43 分钟前
Excel导出实战:从入门到精通 - 构建专业级数据报表的完整指南
开发语言·javascript·excel·有问必答
超浪的晨1 小时前
Java Set 集合详解:从基础语法到实战应用,彻底掌握去重与唯一性集合
java·开发语言·后端·学习·个人开发
workflower1 小时前
活动图描述场景
开发语言·软件工程·需求分析·软件需求·敏捷流程
梦想的初衷~1 小时前
基于现代R语言【Tidyverse、Tidymodel】的机器学习方法
开发语言·机器学习·r语言
liliangcsdn1 小时前
mac mlx大模型框架的安装和使用
java·前端·人工智能·python·macos
香蕉可乐荷包蛋1 小时前
Python学习之路(十三)-常用函数的使用,及优化
开发语言·python·学习