如何用python读取word

Python016

如何用python读取word,第1张

使用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

from docx import Document

# 打开 word文件

f = open('随便写写行.docx', 'rb')

# 读取 word文件内容

document = Document(f)

# 打印 word 文档段落内容2进制列表

# print(document.paragraphs)

# 打开一个txt文档用来写入数据

with open('result2.txt', 'w') as fw:

  # 遍历 word 段落内容列表

  for context in document.paragraphs:

# 以换行符转换成列表

      text = context.text.split('\n')

      # 按行写入,同时换行

      fw.write(f"{text[0]}\n")

      # 打印看看效果

      print(text[0])

f.close()

第一步:获取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)