日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python document_python处理document文档保留原样式

發布時間:2024/9/27 python 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python document_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("","")

text = re.sub(']*>', "", 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 document_python处理document文档保留原样式的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。