首页 > 解决方案 > Pandas:如何读取 docx 文件并将其正确剪切到数据框中?

问题描述

我有 docx 文件,我想以以下格式正确加载到 Doccano:

{"text": "EU rejects German call to boycott British lamb."}
{"text": "Peter Blackburn"}
...
{"text": "President Obama"}

我的目标是使“文本”值的长度大致相同,并且在“文本”值的末尾有一些干净的东西(以点或 ; 结尾)

我考虑过使用这个:https ://gist.github.com/etienned/7539105来阅读 docx 文件并有段落。

这个功能:

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)

接下来将所有内容连接起来以获得大文本并将其剪切以在“文本”值中进行干净的重新分区,但不确定这是否是好方法。

有人可以知道该怎么做吗?

标签: pythonpandas

解决方案


推荐阅读