乔山办公网我们一直在努力
您的位置:乔山办公网 > office365 > <em>python</em>读取word文档内容-python 读取office,python

<em>python</em>读取word文档内容-python 读取office,python

作者:乔山办公网日期:

返回目录:office365


首先下载安装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文件里e69da5e887aae79fa5e98193339面的公式等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)
#不要(),容易引起歧义。

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()

大象关进冰箱需要两步走:

  1.  获取word文件内容
  2.  将获取的内容拆分为对应的业务字段并写入sqlite中

首先我这e799bee5baa6e79fa5e98193e59b9ee7ad94335有个文档,里面包含了驾照考试科四试题。

然后新建sqlite表,以下为表结构:

CREATE TABLE "myDocAnswer" (
"id"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
"title"  TEXT,
"a"  TEXT,
"b"  TEXT,
"c"  TEXT,
"d"  TEXT,
"answer"  TEXT
);

最后将数据导入sqlite中,以下为完整代码:

import docx
import sqlite3

'''
读取docx 数据
'''
document = docx.Document("question.docx")
data=[]  # 定义data列表
item={}
#输出每一段的内容
for param in document.paragraphs:
    # print(param.text)
    if param.text:
        i=param.text[0]
        if i.isdigit():
            item['title']=param.text
        if i=='A':
            item['a'] = param.text[2:]

        if i=='B':
            item['b'] =param.text[2:]

        if i=='C':
            item['c'] = param.text[2:]

        if i=='D':
            item['d'] =param.text[2:]

        if i=='标':
            item['answer'] = param.text[-1:]

    else:
        data.append(item)
        item={}



'''
写入 sqlite

'''

conn = sqlite3.connect("mydocAnswer.db")
c = conn.cursor()
for items in data:
    c.execute("INSERT INTO `myDocAnswer` (`title`,`a`,`b`,`c`,`d`,`answer`) VALUES ('" + items['title'] + "', '" + items['a'] + "', '" + items['b'] + "', '" + items['c'] + "', '" + items['d'] + "', '" + items['answer'] + "')");
    conn.commit()

conn.close()
print('finish')

运行后查看sqlite数据表数据:



使用Python的内部方法open()读取文本文件

try:
    f=open('/file','r')
    print(f.read())
finally:
    if f:
        f.close()

如果读取word文档推荐使用第三方插件,python-docx 可以在官网上下载

使用方式

# -*- coding: cp936 -*-
import docx
document = docx.Document(文件路径)
docText = '\n\n'.join([
    paragraph.text.encode('utf-8') for paragraph in document.paragraphs
])
print docText

相关阅读

  • <em>python</em>+pandas是否能代替excel+vba-python offi

  • 乔山办公网office365
  • 1. 用Excel就学VBA。2. VBA是Excel自带的编程语言,是专门针对办公软件的辅助编程语言。Python代替VBA,请问应该怎么做" src="/uploads/tu/662.jpg" style="width: 400px; height: 267px;" />虽然列了几条,但基
关键词不能为空
极力推荐

ppt怎么做_excel表格制作_office365_word文档_365办公网