python 利用python读取DOC文件
今天小编给各位分享doc文件用什么软件打开的知识,文中也会对其通过python 利用python读取DOC文件和如何用python读取word等多篇文章进行知识讲解,如果文章内容对您有帮助,别忘了关注本站,现在进入正文!
内容导航:
一、python 利用python读取DOC文件
近期公司需要处理一批DOC文件,而在windows系统中,python没有模块能直接读取doc文件。需要先把doc文件批量转成docx文件,再读取操作。linux系统python有模块可直接读取doc文件,下次再分享。
python如何将doc文件如何转docx文件首先安装win32com。
下载地址,https://github.com/mhammond/pywin32/releases。自行下载合适版本安装
转换代码如下
from win32com import client as wcw = wc.Dispatch('Word.Application')# 或用下面方法,使用启动独立的进程# w = wc.DispathchEx('Word.Application')doc = w.Documents.Open('E:/测试.doc')doc.SaveAs('E:/测试.docx', 16)# 参数16必须要写,否则报错
转换完成之后,有多种方法可以读取docx文件里面的内容及格式,例如使用python-docx。
一、如何用python读取word
使用Python的内部方法open()读取文本文件
try:
f=open('/file','r')
print(f.read())
finally:
iff:
f.close()
如果读取word文档推荐使用第三方插件,python-docx 可以在官网上下载
使用方式
#-*-coding:cp936-*-
importdocx
document=docx.Document(文件路径)
docText='\n\n'.join([
paragraph.text.encode('utf-8')forparagraphindocument.paragraphs
])
printdocText
二、python如何读取word文件
>>>defPrintAllParagraphs(doc):
count=doc.Paragraphs.Count
foriinrange(count-1,-1,-1):
pr=doc.Paragraphs[i].Range
printpr.Text
>>>app=my.Office.Word.GetInstance()
>>>doc=app.Documents[0]
>>>PrintAllParagraphs(doc)
1.什么是域
域应用基础
>>>
@staticmethod
defGetInstance():
u'''获取Word应用程序的Application对象'''
importwin32com.client
returnwin32com.client.Dispatch('Word.Application')
my.Office.Word.GetInstance的方法实现如上,是一个使用win32com操纵Word Com的接口的封装
所有Paragraph即段落对象,都是通过Paragraph.Range.Text来访问它的文字的
三、如何在 Linux 上使用 Python 读取 word 文件信息
第一步:获取doc文件的xml组成文件import zipfiledef get_word_xml(docx_filename):
with open(docx_filename) as f:
zip = zipfile.ZipFile(f)
xml_content = zip.read('word/document.xml')
return xml_content
第二步:解析xml为树形数据结构
from lxml import etreedef get_xml_tree(xml_string):
return etree.fromstring(xml_string)
第三步:读取word内容:
def _itertext(self, my_etree):
"""Iterator to go through xml tree's text nodes"""
for node in my_etree.iter(tag=etree.Element):
if self._check_element_is(node, 't'):
yield (node, node.text)def _check_element_is(self, element, type_char):
word_schema = '99999'
return element.tag == '{%s}%s' % (word_schema,type_char)
关于doc文件用什么软件打开的问题,通过《python如何读取word文件》、《如何在 Linux 上使用 Python 读取 word 文件信息》等文章的解答希望已经帮助到您了!如您想了解更多关于doc文件用什么软件打开的相关信息,请到本站进行查找!
爱资源吧版权声明:以上文中内容来自网络,如有侵权请联系删除,谢谢。