采用pycorrector纠错word文件段落,并保存为word文件标红显示出来

以前,我使用pycorrector纠错后,将其保存为txt文本,这样去看纠错的信息就比较困难,所有昨天我想把以前保存为txt文件的纠错信息转为word文件,并将里面要纠错的字词通过改变为红色字体显示出来,搞了很久,一直问百度AI助手,也搞不出来,一开始是全用pywin32模块,这个百度AI掌握得不是很好。今天我采用python-docx模块,就能方便实现。

上面的话,应该不是写的很清楚,实际就是将下面这个txt文件,转为word:

这是以前写的纠错文件。实现的代码是:

# -*- coding: utf-8 -*-
"""
Created on Wed Jan  8 15:05:08 2025

@author: YBK
"""

from docx import Document
from docx.shared import RGBColor

def color_all_samples_red(txt,errs):
    # print(txt)
    # print(errs)
    """
    将段落中所有出现的"sample"(不区分大小写)设置为红色。
    
    :param paragraph: 要处理的段落对象
    """
    if len(txt)>0:
        new_para = doc.add_paragraph()
        
        # 遍历段落中的每个 Run 对象
        index = 0
        while index < len(txt):
            # 检查从当前索引开始的文本是否包含任何目标词语
            found = False
            for word in errs:
                word_len = len(word)
                if txt[index:index+word_len] == word:
                    # 如果找到目标词语,添加一个红色的 Run 到新段落
                    run = new_para.add_run(word.replace('囧',''))
                    run.font.color.rgb = RGBColor(255, 0, 0)
                    index += word_len
                    found = True
                    break
            
            # 如果没有找到目标词语,添加一个包含当前字符的普通 Run 到新段落
            if not found:
                new_para.add_run(txt[index])
                index += 1
    
def insert_symbol_at_position(original_string, position, symbol):
    # 确保位置是有效的
    if position < 0 or position > len(original_string):
        raise ValueError("位置必须在字符串长度范围内(包括末尾)")
    
    # 插入符号
    new_string = (
        original_string[:position] +  # 字符串开头到插入位置之前的部分
        symbol + 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值