【问题标题】:Extracting text from .doc files python [duplicate]从.doc文件python中提取文本[重复]
【发布时间】:2014-02-10 18:16:21
【问题描述】:

我尝试从 .doc 文件中提取文本。文本被提取,但问题是它总是输出这些:

��ࡱ�>�� ln 个字符。

这是我的代码:

    doc=open(input_file,'r')
    read_text_file = doc.readline()
    doc_text = ""
    for line in read_text_file:
        doc_text+=str(line)

    return doc_text

有没有办法将其删除或重新编码为 utf-8?

【问题讨论】:

  • .doc 可能是专有的 Microsoft Word 文件。你不能像纯文本文件一样阅读它。
  • 你能用word打开它们,然后保存到.txt吗?
  • @tk,还没试过那个。安全吗?如果用户没有word应用怎么办?
  • 你有什么要求,能不能把输入格式改成docx:pypi.python.org/pypi/docx
  • @tk 要求能够提取 doc 和 docx 文件中的文本。我已经完成了 Docx 文件。

标签: python


【解决方案1】:

docx 文件只是一个 zip 文件(尝试在其上运行 unzip!),其中包含一堆定义明确的 XML 和附属文件。

import zipfile
from lxml import etree

def get_word(docx_file_name):
    with open(docx_file_name) as f:
        zip = zipfile.SipFile(f)
        xml_content = zip.read('word/document.xml')
return xml_content

#parse the string containing XML into a usable tree
def get_xml_tree(xml_string):
    return etree.fromstring(xml_string)
#xml has functions for traversing the XML tree, but I used the iter instead that 
#will traverse every node given a starting node ”my_etree”, and return every 
#text node and it’s containing text
def _itertext(self, myetree):
    """goes through the xml tree and extracts 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, typr_char):
    word_schema = "http://schemas.openxmlformats.org/wordprocessingml/2006/main"
    return element.tag == '{%s}%s' %(word_schema, type_char)

xml_from_file = self.get_word_xml(wod_filename)
xml_tree = self.get_xml_tree(xml_from_file)
for node, txt in self._itertext(xml_tree):
    print txt

查找更多here

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-04
  • 2011-07-29
  • 1970-01-01
  • 2018-05-14
  • 2017-09-17
相关资源
最近更新 更多