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

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

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

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

python 复制代码
# -*- 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 +                      # 要插入的符号
        original_string[position:]    # 插入位置之后的部分
    )
    
    return new_string

# 创建一个Word文档对象
doc = Document()

with open(r'C:\Users\YBK\Desktop\高考0分作文.txt', 'r', encoding='utf-8') as file:
    datalist = file.readlines() # 全部读入内存
    lines=len(datalist)
    allerr=[]
    ywtxts=[]
    for i in range(0,lines-2):
        dlerr=[]
        if '###########################0#' in datalist[i] and '###########################1#' in datalist[i+2]:
            ywtxts.append(datalist[i-2])            
            txt=datalist[i+1]
            if len(txt) > 3: 
                liststr = txt.replace('\n','').split()
                if len(liststr) == 3:
                    errstr = [liststr[0],liststr[1],liststr[2]]
                    dlerr.append(errstr)
                else:
                    for j in range(0,int(len(liststr)/3)):
                        errstr = [liststr[j*3+0],liststr[j*3+1],liststr[j*3+2]]
                        dlerr.append(errstr)
            allerr.append(dlerr)
        elif '###########################' not in datalist[i] and ('###########################0#' not in datalist[i-1] and '###########################1#' not in datalist[i+1]):
            ywtxts.append(datalist[i])
            allerr.append([])
            
for jj in range(0,len(ywtxts)):
        # 将TXT文件的内容拼接到Word文档的Range对象中
        # range_obj.Text = txt_content + '\n'  # 添加换行符以分隔文件内容
    txt = ywtxts[jj].replace('\n','')
    err = allerr[jj]
    err0 = []
    err1 = ''
    if len(err)>0:
        ii = 0
        err0 = []
        err1 = '★纠错建议:'
        for txterr in err:
            txt = insert_symbol_at_position(txt,int(txterr[2])+ii,'囧')
            ii = ii + 1
            err0.append('囧'+txterr[0])
            err1 = err1 + ' | ' + txterr[0] + '->' + txterr[1]

    # 添加一个包含要查找文本的段落
    # para = doc.add_paragraph(txt)
    color_all_samples_red(txt,err0)
    if len(err0) > 0:
        para = doc.add_paragraph(err1+'★')
    # 调用函数,将段落中的所有"sample"(不区分大小写)设置为红色
    

# 保存Word文档
doc.save(r'C:\Users\YBK\Desktop\高考0分作文_纠错.docx')

运行后,打开docx文件是:

这样就可以方便看出,那些文字或词语是错误的。

做了这个py程序,我发现其实可以直接从word文件直接纠错,再打开纠错后的word文件。word可以按段落来纠错。

python 复制代码
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 25 10:12:58 2024

@author: YBK
"""
import tkinter as tk
import windnd
from tkinter.messagebox import showinfo
import os
import comtypes.client
from pycorrector import Corrector
import subprocess
from docx import Document
from docx.shared import RGBColor
 

def get_file_extension(file_path):
    return os.path.splitext(file_path)[-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 +                      # 要插入的符号
        original_string[position:]    # 插入位置之后的部分
    )
    
    return new_string
def jc_doc_file(file_path):
    # 创建一个Word文档对象
    doc000 = Document()
    def color_all_samples_red(txt,errs):
        # print(len(txt))
        # print(errs)
        if len(txt)>1:
            new_para = doc000.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
    
    # 创建一个Word应用程序对象
    word = comtypes.client.CreateObject('Word.Application')
    word.Visible = 0  # 不显示Word界面
 
    # 打开Word文档
    doc = word.Documents.Open(file_path)
 
    # 读取文档内容
    for paragraph in doc.Paragraphs:
        m=Corrector()
        corrected_sent=m.correct(paragraph.Range.Text)
        e = corrected_sent.get('errors') #获取错误的信息在###二行的写出来
        aa = []
        for ee in e:
            for eee in list(ee):
                aa.append(eee)
        txt = paragraph.Range.Text.replace('\n','').replace('\r','')
        err = e
        err0 = []
        err1 = ''
        if len(err)>0:
            ii = 0
            err0 = []
            err1 = '★纠错建议:'
            for txterr in err:
                # print(txterr)
                txt = insert_symbol_at_position(txt,int(txterr[2])+ii,'囧')
                ii = ii + 1
                err0.append('囧'+txterr[0])
                err1 = err1 + ' | ' + txterr[0] + '->' + txterr[1]

        # 添加一个包含要查找文本的段落
        # para = doc.add_paragraph(txt)
        
        color_all_samples_red(txt,err0)
        if len(err0) > 0:
            doc000.add_paragraph(err1+'★')

        with open(file_path.replace(get_file_extension(file_path),'.txt'), "a", encoding='utf-8') as file:
            if len(aa) > 0:
                file.write(paragraph.Range.Text + "\n ############################0# \n" + 
                           " ".join('%s' % id for id in aa) + 
                           "\n ############################1# \n")
            else:
                file.write(paragraph.Range.Text)
        del(m)
    # 关闭文档并退出Word应用程序
    doc.Close()
    word.Quit()
    doc000.save(file_path.replace(get_file_extension(file_path),'_纠错.docx'))    
    return file_path.replace(get_file_extension(file_path),'_纠错.docx')
 
def dragged_files(files):
    fileurl = ''
    if len(files) > 1:
        # print("请拖放一个文件!")
        showinfo("提示","请拖放一个文件!")
    else:
        # print(files[0].decode('gbk'))
        fileurl = files[0].decode('gbk')
        # print(os.path.splitext(fileurl)[1])
    if fileurl != '' and os.path.splitext(fileurl)[1] in ('.doc','.docx'):
        wordpath = fileurl
        message.config(text='当前拖放的文件路径为:\n' + wordpath + '\n 等下记得关闭wps。')
        outwordpath = jc_doc_file(wordpath)       
        wps_executable_path = r'C:\Users\YBK\AppData\Local\kingsoft\WPS Office\ksolaunch.exe'
        subprocess.run([wps_executable_path, outwordpath])
        message.config(text='当前纠错的文件路径为:\n' + wordpath + '\n 等下记得关闭wps。')

if __name__ == '__main__':
    rootWindow = tk.Tk()
    rootWindow.title("拖放Word文件进行纠错")
    rootWindow.geometry("300x120")
    message = tk.Message(rootWindow, width=300, text="当前未拖放文件。")
    message.pack()
    windnd.hook_dropfiles(rootWindow , func=dragged_files)
    rootWindow.mainloop()

拖放文件到这里就行:

等下(应该是等很久),就会用wps打开word文件(上面代码的wps程序路径要换成你们的)

相关推荐
AI探索者16 小时前
LangGraph StateGraph 实战:状态机聊天机器人构建指南
python
AI探索者16 小时前
LangGraph 入门:构建带记忆功能的天气查询 Agent
python
FishCoderh17 小时前
Python自动化办公实战:批量重命名文件,告别手动操作
python
躺平大鹅17 小时前
Python函数入门详解(定义+调用+参数)
python
曲幽18 小时前
我用FastAPI接ollama大模型,差点被asyncio整崩溃(附对话窗口实战)
python·fastapi·web·async·httpx·asyncio·ollama
两万五千个小时1 天前
落地实现 Anthropic Multi-Agent Research System
人工智能·python·架构
哈里谢顿1 天前
Python 高并发服务限流终极方案:从原理到生产落地(2026 实战指南)
python
用户8356290780512 天前
无需 Office:Python 批量转换 PPT 为图片
后端·python
markfeng82 天前
Python+Django+H5+MySQL项目搭建
python·django
GinoWi2 天前
Chapter 2 - Python中的变量和简单的数据类型
python