获取错误的特殊字符读取docx文件

时间:2014-07-23 10:55:22

标签: python

我正在尝试使用以下代码从.docx获取文本,但问题是文本包含特殊字符(例如“ç”或“á”),并且代码未读取文件correclty

try:
    from xml.etree.cElementTree import XML
except ImportError:
    from xml.etree.ElementTree import XML
import zipfile


"""
Module that extract text from MS XML Word document (.docx).
(Inspired by python-docx <https://github.com/mikemaccana/python-docx>)
"""

WORD_NAMESPACE = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
PARA = WORD_NAMESPACE + 'p'
TEXT = WORD_NAMESPACE + 't'


def get_docx_text(path):
    """
    Take the path of a docx file as argument, return the text in unicode.
    """
    document = zipfile.ZipFile(path)
    xml_content = document.read('word/document.xml')
    document.close()
    tree = XML(xml_content)

    paragraphs = []
    for paragraph in tree.getiterator(PARA):
        texts = [node.text
                 for node in paragraph.getiterator(TEXT)
                 if node.text]
        if texts:
            paragraphs.append(''.join(texts))

    return '\n\n'.join(paragraphs)


if __name__ == '__main__':
    doc = def_get_docx_text('teste.docx')
    print doc.split('\n')

在这个简短的例子中,原始文本是这样的:

A titulação genérica de Administração Pública

但我得到了这个:

01 A titula\xe7\xe3o gen\xe9rica de Administra\xe7\xe3o

1 个答案:

答案 0 :(得分:1)

您正在打印列表;在Python中,然后使用repr()输出显示容器内容。 u'A titula\xe7\xe3o gen\xe9rica de Administra\xe7\xe3o'是Unicode字符串值的Python字符串文字语法;此格式专为调试目的而设计,可以直接粘贴到Python解释器中以重新创建原始值,而无需担心编码问题:

>>> line = u'A titula\xe7\xe3o gen\xe9rica de Administra\xe7\xe3o'
>>> line
u'A titula\xe7\xe3o gen\xe9rica de Administra\xe7\xe3o'
>>> print line
A titulação genérica de Administração

改为打印单个字符串:

for line in doc.split('\n'):
    print line

或重新加入字符串,例如:

print ' '.join(doc.split('\n'))