python读取word文档的方法

python读取word文档的方法,第1张

概述本文实例讲述了python读取word文档方法。分享给大家供大家参考。具体如下:

本文实例讲述了python读取word文档的方法。分享给大家供大家参考。具体如下:

首先下载安装win32com

from win32com import clIEnt as wcword = wc.dispatch('Word.Application')doc = word.documents.Open('c:/test')doc.SaveAs('c:/test.text',2)doc.Close()word.Quit()

这种方式产生的text文档,不能用python用普通的r方式读取,为了让python可以用r方式读取,应当写成

doc.SaveAs('c:/test',4)

注意:系统执行完成后,会自动产生文件后缀txt(虽然没有指明后缀)。
在xp系统下面,应当,

open(r'c:\text','r')wdFormatdocument = 0wdFormatdocument97 = 0wdFormatdocumentDefault = 16wdFormatDOSText = 4wdFormatDOSTextlineBreaks = 5wdFormatEncodedText = 7wdFormatFilteredHTML = 10wdFormatFlatXML = 19wdFormatFlatXMLMacroEnabled = 20wdFormatFlatXMLTemplate = 21wdFormatFlatXMLTemplateMacroEnabled = 22wdFormatHTML = 8wdFormatpdf = 17wdFormatRTF = 6wdFormatTemplate = 1wdFormatTemplate97 = 1wdFormatText = 2wdFormatTextlineBreaks = 3wdFormatUnicodeText = 7wdFormatWebarchive = 9wdFormatXML = 11wdFormatXMLdocument = 12wdFormatXMLdocumentMacroEnabled = 13wdFormatXMLTemplate = 14wdFormatXMLTemplateMacroEnabled = 15wdFormatXPS = 18

照着字面意思应该能对应到相应的文件格式,如果你是office 2003可能支持不了这么多格式。word文件转HTML有两种格式可选wdFormatHTML、wdFormatFilteredHTML(对应数字 8、10),区别是如果是wdFormatHTML格式的话,word文件里面的公式等ole对象将会存储成wmf格式,而选用 wdFormatFilteredHTML的话公式图片将存储为gif格式,而且目测可以看出用wdFormatFilteredHTML生成的HTML 明显比wdFormatHTML要干净许多。

当然你也可以用任意一种语言通过com来调用office API,比如PHP.

from win32com import clIEnt as wcword = wc.dispatch('Word.Application')doc = word.documents.Open(r'c:/test1.doc')doc.SaveAs('c:/test1.text',4)doc.Close()
import restrings=open(r'c:\test1.text','r').read()result=re.findall('\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)|\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)',strings)chan=re.sub('\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)|\(\s*[A-D]\s*\)|\(\xa1*[A-D]\xa1*\)','()',strings)question=open(r'c:\question','a+')question.write(chan)question.close()answer=open(r'c:\answeronly','a+')for i,a in enumerate(result): m=re.search('[A-D]',a) answer.write(str(i+1)+' '+m.group()+'\n')answer.close()chan=re.sub(r'\xa3\xa8\s*[A-D]\s*\xa3\xa9',strings)#不要(),容易引起歧义。

希望本文所述对大家的Python程序设计有所帮助。

总结

以上是内存溢出为你收集整理的python读取word文档的方法全部内容,希望文章能够帮你解决python读取word文档的方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/langs/1203278.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-06-04
下一篇2022-06-04

发表评论

登录后才能评论

评论列表(0条)

    保存