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实现冒泡,插入,选择排序简单实例
Aug 18 Python
浅谈Python程序与C++程序的联合使用
Apr 07 Python
python之Character string(实例讲解)
Sep 25 Python
Python实现针对给定字符串寻找最长非重复子串的方法
Apr 21 Python
对pandas数据判断是否为NaN值的方法详解
Nov 06 Python
Python内置加密模块用法解析
Nov 25 Python
PyCharm+Pipenv虚拟环境开发和依赖管理的教程详解
Apr 16 Python
Python API 操作Hadoop hdfs详解
Jun 06 Python
vscode+PyQt5安装详解步骤
Aug 12 Python
Python urllib3软件包的使用说明
Nov 18 Python
Python+OpenCV实现在图像上绘制矩形
Mar 21 Python
Python os和os.path模块详情
Apr 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操作csv文件代码实例汇总
2014/09/22 PHP
php格式化金额函数分享
2015/02/02 PHP
使用PHP生成二维码的方法汇总
2015/07/22 PHP
动手学习无线电
2021/03/10 无线电
基于jQuery实现点击同时更改两个iframe的网址
2010/07/01 Javascript
json数据处理技巧(字段带空格、增加字段、排序等等)
2013/06/14 Javascript
JS在TextArea光标位置插入文字并实现移动光标到文字末尾
2013/06/21 Javascript
Bootstrap自定义文件上传下载样式
2016/05/26 Javascript
详解Vue方法与事件
2017/03/09 Javascript
node.js实现的装饰者模式示例
2017/09/06 Javascript
JS实现的按钮点击颜色切换功能示例
2017/10/19 Javascript
js使用xml数据载体实现城市省份二级联动效果
2017/11/08 Javascript
swiper Scrollbar滚动条组件详解
2019/09/08 Javascript
vue 添加和编辑用同一个表单,el-form表单提交后清空表单数据操作
2020/08/03 Javascript
微信小程序实现聊天室
2020/08/21 Javascript
微信小程序自定义底部弹出框功能
2020/11/18 Javascript
[01:06:07]2014 DOTA2国际邀请赛中国区预选赛5.21 DT VS CIS
2014/05/22 DOTA
[43:24]完美世界DOTA2联赛PWL S3 INK ICE vs DLG 第二场 12.12
2020/12/17 DOTA
python网络编程学习笔记(五):socket的一些补充
2014/06/09 Python
用Python实现一个简单的线程池
2015/04/07 Python
python获取一组汉字拼音首字母的方法
2015/07/01 Python
Python的“二维”字典 (two-dimension dictionary)定义与实现方法
2016/04/27 Python
Python多线程threading和multiprocessing模块实例解析
2018/01/29 Python
python之文件读取一行一行的方法
2018/07/12 Python
django有哪些好处和优点
2020/09/01 Python
阳光体育:Sunny Sports(购买露营和远足设备)
2018/08/07 全球购物
请说出几个常用的异常类
2013/01/08 面试题
计算机专业自荐信
2013/10/14 职场文书
清华大学自主招生自荐信
2014/01/29 职场文书
高中军训感言800字
2014/03/05 职场文书
2014领导干部学习焦裕禄同志先进事迹思想汇报
2014/09/19 职场文书
停车场管理协议书范本
2014/10/08 职场文书
2014年幼儿园教研工作总结
2014/12/04 职场文书
挂职个人工作总结
2015/03/05 职场文书
义卖募捐活动总结
2015/05/09 职场文书
导游词之日本富士山
2020/01/06 职场文书