python 處理document文檔 保留原樣式


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()

————————————————
版權聲明:本文為CSDN博主「Cocktail_py」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/Cocktail_py/article/details/101149901


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM