python处理document文档保留原样式


Posted in Python onSeptember 23, 2019

document文档格式、线段、图片、页眉页脚等都不变,供大家参考,具体内容如下

# -*- coding: utf-8 -*-
# @Time  : 2019/5/6 11:46
# @Author :
"""
# 利用python-docx替换文章中的内容

pip install python-docx
# 格式、线段、图片、页眉页脚等都不变
# python-docx 在处理超链接的问题时,可以参考一下链接对源码进行修改
https://github.com/python-openxml/python-docx/issues/85

# 具体修改操作如下
\site-packages\docx\oxml\__init__.py

# 需要新增的代码
def remove_hyperlink_tags(xml):
  import re
  text = xml.decode('utf-8')
  text = text.replace("</w:hyperlink>","")
  text = re.sub('<w:hyperlink[^>]*>', "", text)
  return text.encode('utf-8')

# 需要修改的源码
def parse_xml(xml):
  root_element = etree.fromstring(remove_hyperlink_tags(xml), oxml_parser)
  return root_element
"""

import os

from docx import Document
from win32com import client

# 自己写的逐句翻译包
import doc_scan


def pre_document(filename):
  """
  由于python_docx(只能读取.docx文件,不能读取.doc文件)
  将对应文件夹下的doc文件转为docx文件
  :param filename: 文件的绝对路径
  :return:
  """

  file_tuple = os.path.splitext(filename)
  if file_tuple[1] == '.doc':
    word = client.Dispatch('Word.Application')
    doc = word.Documents.Open(filename) # 目标路径下的文件
    doc.SaveAs(file_tuple[0] + ".docx", 16) # 转化后路径下的文件
    doc.Close()
    word.Quit()
    # 把源文件删除
    os.remove(filename)


def read_document():
  """
  原文文章为中文,然后将中文逐句翻译成英文,把英文替换原来的中文,保留文章的原样式
  :return:
  """
  # 遍历doc文件下的所有的文件
  path = os.path.dirname(os.path.abspath(__file__)) + '\doc'
  for f in os.listdir(path):
    file = "%s\%s" % (path, f)
    # 对源文件进行预处理
    pre_document(file)
    document = Document(file)
    for num, paragraph in enumerate(document.paragraphs):
      # 获取每段中的文字
      old_text = paragraph.text.strip()
      if old_text:
        inlines = paragraph.runs
        if inlines:
          # 将原有的文章里面的内容为空
          for li, inli in enumerate(inlines):
            inlines[li].text = inlines[li].text.replace(inlines[li].text, '')
          new_text = doc_scan.Scan(old_text)

          # 把翻译好的文章句子 替换到 零号位置上面
          inlines[0].text = new_text
    # 保存文件,覆盖操作
    document.save(file)


# 将document中的图片下载到本地
# document = Document(file)
# for shape in document.inline_shapes:
#   contentID = shape._inline.graphic.graphicData.pic.blipFill.blip.embed
#   contentType = document.part.related_parts[contentID].content_type
#   if not contentType.startswith('image'):
#     continue
#   imgName = basename(document.part.related_parts[contentID].partname)
#   imgData = document.part.related_parts[contentID]._blob
#   with open(imgName,'wb') as fp:
#     fp.write(imgData)

if __name__ == '__main__':
  read_document()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
python中定义结构体的方法
Mar 04 Python
python实现定制交互式命令行的方法
Jul 03 Python
基于python的Tkinter实现一个简易计算器
Dec 31 Python
python 读取DICOM头文件的实例
May 07 Python
Python生成器的使用方法和示例代码
Mar 04 Python
pandas删除行删除列增加行增加列的实现
Jul 06 Python
Python List列表对象内置方法实例详解
Oct 22 Python
pytorch 数据处理:定义自己的数据集合实例
Dec 31 Python
pytorch实现MNIST手写体识别
Feb 14 Python
使用bandit对目标python代码进行安全函数扫描的案例分析
Jan 27 Python
浅谈Python响应式类库RxPy
Jun 14 Python
Python List remove()实例用法详解
Aug 02 Python
python 进程间数据共享multiProcess.Manger实现解析
Sep 23 #Python
python程序 线程队列queue使用方法解析
Sep 23 #Python
python程序 创建多线程过程详解
Sep 23 #Python
详解python播放音频的三种方法
Sep 23 #Python
Python进程间通信 multiProcessing Queue队列实现详解
Sep 23 #Python
python程序中的线程操作 concurrent模块使用详解
Sep 23 #Python
Python3 pandas 操作列表实例详解
Sep 23 #Python
You might like
php切割页面div内容的实现代码分享
2012/07/31 PHP
PHP实现的汉字拼音转换和公历农历转换类及使用示例
2014/07/01 PHP
PHP实现的限制IP投票程序IP来源分析
2016/05/04 PHP
基于jQuery实现点击同时更改两个iframe的网址
2010/07/01 Javascript
js的匿名函数使用介绍
2013/12/11 Javascript
JavaScript异步回调的Promise模式封装实例
2014/06/07 Javascript
javaScript中slice函数用法实例分析
2015/06/08 Javascript
jquery实现动静态条形统计图
2015/08/17 Javascript
js实现的tab标签切换效果代码分享
2015/08/25 Javascript
总结Javascript中的隐式类型转换
2016/08/24 Javascript
Vue中div contenteditable 的光标定位方法
2018/08/25 Javascript
jQuery实现的自定义轮播图功能详解
2018/12/28 jQuery
基于three.js实现的3D粒子动效实例代码
2019/04/09 Javascript
vue中使用[provide/inject]实现页面reload的方法
2019/09/30 Javascript
JavaScript将数组转换为链表的方法
2020/02/16 Javascript
[42:20]Winstrike vs VGJ.S 2018国际邀请赛淘汰赛BO3 第二场 8.23
2018/08/24 DOTA
python下如何让web元素的生成更简单的分析
2008/07/17 Python
Python标准库之循环器(itertools)介绍
2014/11/25 Python
Python运算符重载详解及实例代码
2017/03/07 Python
python Socket之客户端和服务端握手详解
2017/09/18 Python
Python、 Pycharm、Django安装详细教程(图文)
2019/04/12 Python
python文件写入write()的操作
2019/05/14 Python
Python3日期与时间戳转换的几种方法详解
2019/06/04 Python
Python定时任务工具之APScheduler使用方式
2019/07/24 Python
英国潮流网站:END.(全球免邮)
2017/01/16 全球购物
英国领先的高街书籍专家:Waterstones
2018/02/01 全球购物
英国高街电视:High Street TV
2018/05/22 全球购物
越南综合购物网站:Lazada越南
2019/06/10 全球购物
泰国最新活动和优惠:Megatix
2020/05/07 全球购物
PHP如何自定义函数
2016/09/16 面试题
制药工程专业应届生求职信
2013/09/24 职场文书
八年级语文教学反思
2014/02/11 职场文书
会计与审计专业自荐信范文
2014/03/15 职场文书
同学聚会策划方案
2014/06/06 职场文书
安全承诺书
2015/01/19 职场文书
2015年全国保险公众宣传日活动方案
2015/05/06 职场文书