You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Word文档脱敏脚本参数配置求助:路径与输出设置指导

Word文档脱敏Python脚本使用指南

1. 先安装依赖库

运行以下命令安装处理Word文档的必要依赖:

pip install python-docx

2. 完整可运行代码

原代码缺少关键辅助函数,以下是补全后的完整可运行版本:

import re
from docx import Document
from docx.shared import RGBColor

def redact_colors(color: str = None):
    # 默认用黑色脱敏(文字与背景同色,完全隐藏内容)
    if not color or color.lower() == "black":
        txt_color = RGBColor(0, 0, 0)
        background_color = RGBColor(0, 0, 0)
    # 可选灰色脱敏(半隐藏效果)
    elif color.lower() == "gray":
        txt_color = RGBColor(128, 128, 128)
        background_color = RGBColor(128, 128, 128)
    else:
        # 无效颜色默认 fallback 到黑色
        txt_color = RGBColor(0, 0, 0)
        background_color = RGBColor(0, 0, 0)
    return txt_color, background_color

def process_matches(match_pairs, text):
    matches = [0]
    highlights = []
    current_pos = 0
    for start, end in match_pairs:
        if start > current_pos:
            matches.append(start)
            highlights.append(False)
        matches.append(end)
        highlights.append(True)
        current_pos = end
    if current_pos < len(text):
        matches.append(len(text))
        highlights.append(False)
    return highlights, matches

def split_run_by(paragraph, run, split_positions):
    split_positions.sort(reverse=True)
    new_runs = []
    current_run = run
    for pos in split_positions:
        if pos < len(current_run.text):
            new_run = current_run.split(pos)
            new_runs.insert(0, new_run)
    new_runs.insert(0, current_run)
    return new_runs

def redact_document(input_path: str, output_path: str, pattern: list, color: str = None):
    # 获取脱敏用的文字颜色和背景色
    txt_color, background_color = redact_colors(color)

    # 打开输入文档
    doc = Document(input_path)
    # 遍历所有段落
    for para in doc.paragraphs:
        # 反向遍历段落中的文本块(避免拆分后索引混乱)
        run_index = len(para.runs) - 1
        while run_index > -1:
            run = para.runs[run_index]
            # 查找所有匹配脱敏词汇的位置
            match_pairs = [(match.start(), match.end()) for match in re.finditer('|'.join(pattern), run.text)]
            # 处理匹配位置,生成拆分和高亮标记
            highlights, matches = process_matches(match_pairs, run.text)
            # 只有找到匹配内容时才进行脱敏
            if len(highlights) > 0 and len(matches) > 0:
                if len(highlights) != len(matches) - 1:
                    raise ValueError('匹配内容与高亮标记数量不匹配')
                else:
                    if len(matches) == 2:  # 当前文本块全是脱敏内容
                        run.font.highlight_color = background_color
                        run.font.color.rgb = txt_color
                    else:
                        # 拆分文本块,只高亮匹配的部分
                        new_runs = split_run_by(para, run, matches[1:-1])
                        for highlight, run in zip(highlights, new_runs):
                            if highlight:
                                run.font.highlight_color = background_color
                                run.font.color.rgb = txt_color
            run_index -= 1
    # 保存脱敏后的文档
    doc.save(output_path)

# -------------------------- 参数填写位置 --------------------------
if __name__ == "__main__":
    # 1. 输入文档路径:替换为你的原始Word文件路径
    input_doc_path = "C:/Users/你的用户名/Desktop/原始文档.docx"
    # 2. 输出文档路径:脱敏后文件的保存路径(不要和原文件路径重复)
    output_doc_path = "C:/Users/你的用户名/Desktop/脱敏后文档.docx"
    # 3. 脱敏词汇列表:将需要隐藏的词汇、手机号、地址等放入列表
    redact_words = ["张三", "138xxxx1234", "北京市朝阳区XX大厦"]
    # 4. 脱敏颜色:可选"black"(默认)或"gray",留空则用黑色
    redact_color = "black"

    # 调用脱敏函数
    redact_document(input_doc_path, output_doc_path, redact_words, redact_color)

3. 参数填写说明

  • 输入路径(input_doc_path):
    填写原始Word文档的完整路径,Windows系统可写为"C:/Users/xxx/Desktop/test.docx",若脚本和文档在同一文件夹,可直接用相对路径"./test.docx"。
  • 输出路径(output_doc_path):
    填写脱敏后文档的保存位置,注意不要与原文件路径重复,防止覆盖原始文件。
  • 脱敏词汇列表(redact_words):
    把所有需要隐藏的内容(如姓名、手机号、地址、敏感术语)放进列表,格式为["内容1", "内容2"]。
  • 脱敏颜色(redact_color):
    可选参数,默认用黑色(文字与背景同色,完全隐藏),也可填"gray"实现灰色半隐藏效果。

4. 运行脚本

填好所有参数后,直接运行该Python脚本,即可生成脱敏后的Word文档。

内容的提问来源于stack exchange,提问作者Dion

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 14:05:23