⑴ 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
= 22
wdFormatHTML = 8
wdFormatPDF = 17
wdFormatRTF = 6
wdFormatTemplate = 1
wdFormatTemplate97 = 1
wdFormatText = 2
wdFormatTextLineBreaks = 3
wdFormatUnicodeText = 7
wdFormatWebArchive = 9
wdFormatXML = 11
wdFormatXMLDocument = 12
= 13
wdFormatXMLTemplate = 14
= 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讀取word文檔內容
import fnmatch, os, sys, win32com.client
readpath=r'D:\123'
wordapp = win32com.client.gencache.EnsureDispatch("Word.Application")
try:
for path, dirs, files in os.walk(readpath):
for filename in files:
if not fnmatch.fnmatch(filename, '*.docx'):continue
doc = os.path.abspath(os.path.join(path,filename))
print 'processing %s...' % doc
wordapp.Documents.Open(doc)
docastext = doc[:-4] + 'txt'
wordapp.ActiveDocument.SaveAs(docastext,FileFormat=win32com.client.constants.wdFormatText)
wordapp.ActiveDocument.Close()
finally:
wordapp.Quit()
print 'end'
f=open(r'd:\123\test.txt','r')
for line in f.readlines():
print line.decode('gbk')
f.close()