Technology Sharing

  • 首页
  • 资料分享
  • 在线工具
    • 随机密码生成器
  • 介绍
  • RSS
  • privacy
  • 云产品推广
    • 腾讯云
    • 阿里云
Share IT knowledge
  1. 首页
  2. linux
  3. 正文

Python自动化 | 比对两份Excel/Word文件

2022年9月30日 240点热度 0人点赞 0条评论

如果你经常与Excel或Word打交道,那么从两份表格/文档中找到不一样的元素是一件让人很头疼的工作,当然网上有很多方法、第三方软件教你如何对比两份文件。本文就将以两份真实的Excel/Word文件为例,讲解如何使用Python光速对比并提取文件中的不同之处!

比较Excel

Excel用例

可以看到上方两个Excel表格中共有四处不同,现在我们使用Python来快速定位这五处不同。

import pandas as pd          #没有pandas模块,记得安装
import numpy as np
df1 = pd.read_excel('data1.xlsx')
df2 = pd.read_excel('data2.xlsx')

comparison_values = df1.values == df2.values
rows,cols=np.where(comparison_values==False)
for item in zip(rows,cols):
    df1.iloc[item[0], item[1]] = '{} --> {}'.format(df1.iloc[item[0], item[1]],df2.iloc[item[0], item[1]])
df1.to_excel('diff.xlsx',index=False,header=True)

现在就生成了一个新的Excel来提示我们哪里发生了变化

比较Word

我们还是创建两份有区别的Word文档

from docx import Document    # 需安装python-docx模块
import re
def getText(wordname):
    '''
    提取文字
    '''
    d = Document(wordname)
    texts = []
    for para in d.paragraphs:
        texts.append(para.text)
    return texts

def is_Chinese(word):
    '''
    识别中文
    '''
    for ch in word:
        if '\u4e00' <= ch <= '\u9fff':
            return True
    return False

def msplit(s, seperators = ',|\.|\?|,|。|?|!|、'):
    '''
    根据标点符号分句
    '''
    return re.split(seperators, s)

def readDocx(docfile):
    '''
    读取文档
    '''
    print(f"======正在读取{docfile}======")
    paras = getText(docfile)
    segs = []
    for p in paras:
        temp = []
        for s in msplit(p):
            if len(s) > 2:
                temp.append(s.replace(' ', ""))
        if len(temp) > 0:
            segs.append(temp)
    return segs

def comparsion(doc1,doc2,p,s):
    if doc1 == doc2:
        print('两个word完全一致')
    else:
        if doc1[p][s] != doc2[p][s]:
            print(f"第{p+1}段,第{s+1}句不相同: {doc1[p][s]} ----> {doc2[p][s]}")


doc1 = readDocx('data1.docx')
doc2 = readDocx('data2.docx')

for p  in  range(len(doc1)):
    for s in range(len(doc1[p])):
        comparsion(doc1, doc2, p, s)

打赏微海报分享
标签: 暂无
最后更新:2022年9月30日

nico

Linux运维工程师 软考网络工程师 && 软考信息安全工程师

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

nico

Linux运维工程师
软考网络工程师 && 软考信息安全工程师

最新 热点 随机
最新 热点 随机
linux部署JDK环境 [Solved] MariaDB import issue: Error at line 1: Unknown command '\-'. Could not retrieve mirrorlist http://mirrorlist.centos.org/ CentOS 7 Kubernetes如何删除卡在“Terminating”状态的命名空间 解决GitLab Runner签名无效 如何禁用 Ubuntu "Daemons using outdated libraries" 弹出窗口
Nginx部署ngx_pagespeed模块加速网站 Git Bash下使用rsync Web3.0: 开启去中心化的互联网时代 使用 Docker Search 命令的过滤选项来查找容器镜像 Python操作Excel (openpyxl模块) Supervisor – 简化进程管理的得力工具
最近评论
woodcockkienzlelsj8o9+73s48g9rr3m0@gmail.com 发布于 10 个月前(07月17日) necessitatibus corporis et odit nam quo harum et c...
RonaldG 发布于 10 个月前(07月07日) Very interesting topic, thank you for putting up.&...
小黑 发布于 1 年前(12月28日) 不错
nico 发布于 2 年前(02月09日) 嘻嘻嘻!!!
Bruse 发布于 2 年前(02月09日) 我来啦!!!
nico 发布于 2 年前(12月10日) 方便查询
Justin 发布于 2 年前(12月10日) 写的很好,谢谢分享!我 Mark 一下~
nico 发布于 3 年前(11月18日) 主题的原因吧
Justin 发布于 3 年前(09月22日) 这篇文章的质量很高呀!写得很详细~ 话说你的文章是隐藏了发布时间吗?
Justin 发布于 3 年前(08月27日) 好家伙,这标题乍一看还以为你打算进军英文技术写作领域了🤓

COPYRIGHT © 2023 Technology Sharing. ALL RIGHTS RESERVED.

备案图标 皖公网安备34132402000202 皖ICP备2023004851号-1