python读取word文档的方法

yipeiwu_com5年前Python基础

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

首先下载安装win32com

from win32com import client as wc
word = 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 = 0
wdFormatDocument97 = 0
wdFormatDocumentDefault = 16
wdFormatDOSText = 4
wdFormatDOSTextLineBreaks = 5
wdFormatEncodedText = 7
wdFormatFilteredHTML = 10
wdFormatFlatXML = 19
wdFormatFlatXMLMacroEnabled = 20
wdFormatFlatXMLTemplate = 21
wdFormatFlatXMLTemplateMacroEnabled = 22
wdFormatHTML = 8
wdFormatPDF = 17
wdFormatRTF = 6
wdFormatTemplate = 1
wdFormatTemplate97 = 1
wdFormatText = 2
wdFormatTextLineBreaks = 3
wdFormatUnicodeText = 7
wdFormatWebArchive = 9
wdFormatXML = 11
wdFormatXMLDocument = 12
wdFormatXMLDocumentMacroEnabled = 13
wdFormatXMLTemplate = 14
wdFormatXMLTemplateMacroEnabled = 15
wdFormatXPS = 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 wc
word = wc.Dispatch('Word.Application')
doc = word.Documents.Open(r'c:/test1.doc')
doc.SaveAs('c:/test1.text', 4)
doc.Close()
import re
strings=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之pymysql模块简单应用示例代码

众所周知,想要在python程序中执行SQL语句需要使用第三方模块:pymysql。 下面,我将为大家简述一下pymysql第三方库的安装到使用的大体流程。 pymysql的安装 1....

python输入多行字符串的方法总结

Python中输入多行字符串: 方法一:使用三引号 >>> str1 = '''Le vent se lève, il faut tenter de vivre....

centos 下面安装python2.7 +pip +mysqld

python2.7 复制代码 代码如下: wget http://www.python.org/ftp/python/2.7.6/Python-2.7.6.tar.xz yum inst...

Python底层封装实现方法详解

这篇文章主要介绍了Python底层封装实现方法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 事实上,python封装特性的实现纯...

python 反向输出字符串的方法

python 反向输出字符串的方法 方法一:采用列表reversed函数 class Solution(object): def reverse_string(self, s):...