采用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程序路径要换成你们的)

相关推荐
张3蜂8 分钟前
深入理解 Python 的 frozenset:为什么要有“不可变集合”?
前端·python·spring
皮卡丘不断更21 分钟前
手搓本地 RAG:我用 Python 和 Spring Boot 给 AI 装上了“实时代码监控”
人工智能·spring boot·python·ai编程
爱打代码的小林36 分钟前
基于 MediaPipe 实现实时面部关键点检测
python·opencv·计算机视觉
极客小云1 小时前
【ComfyUI API 自动化利器:comfyui_xy Python 库使用详解】
网络·python·自动化·comfyui
闲人编程1 小时前
Elasticsearch搜索引擎集成指南
python·elasticsearch·搜索引擎·jenkins·索引·副本·分片
痴儿哈哈1 小时前
自动化机器学习(AutoML)库TPOT使用指南
jvm·数据库·python
花酒锄作田2 小时前
SQLAlchemy中使用UPSERT
python·sqlalchemy
SoleMotive.2 小时前
一个准程序员的健身日志:用算法调试我的增肌计划
python·程序员·健身·职业转型
亓才孓2 小时前
[Properties]写配置文件前,必须初始化Properties(引用变量没执行有效对象,调用方法会报空指针错误)
开发语言·python
Bruk.Liu2 小时前
(LangChain 实战14):基于 ChatMessageHistory 自定义实现对话记忆功能
人工智能·python·langchain·agent