65

我正在尝试使用python-docx模块(pip install python-docx),但它似乎非常令人困惑,因为在github repo测试示例中他们使用的是opendocx函数,但在readthedocs中他们使用的是Document类。即使他们只展示了如何将文本添加到 docx 文件,而不是读取现有文件?

第一个 ( opendocx) 不起作用,可能已弃用。对于第二种情况,我试图使用:

from docx import Document

document = Document('test_doc.docx')
print(document.paragraphs)

它返回了一个列表<docx.text.Paragraph object at 0x... >

然后我做了:

for p in document.paragraphs:
    print(p.text)

它返回了所有文本,但几乎没有什么遗漏。控制台上的文本中不存在所有 URL(CTRL+CLICK 转到 URL)。

问题是什么?为什么缺少 URL?

我如何在不迭代循环的情况下获得完整的文本(类似于open().read()

4

8 回答 8

67

你可以试试这个

import docx

def getText(filename):
    doc = docx.Document(filename)
    fullText = []
    for para in doc.paragraphs:
        fullText.append(para.text)
    return '\n'.join(fullText)
于 2016-03-08T15:28:19.077 回答
19

您可以使用从 python-docx 改编的python-docx2txt,但也可以从链接、页眉和页脚中提取文本。它还可以提取图像。

于 2015-10-29T02:59:23.980 回答
15

你也可以试试这个

from docx import Document

document = Document('demo.docx')
for para in document.paragraphs:
    print(para.text)
于 2017-04-21T05:10:35.100 回答
13

无需安装python-docx

docx基本上是一个 zip 文件,其中包含多个文件夹和文件。在下面的链接中,您可以找到一个从docx文件中提取文本的简单函数,无需依赖,python-docx后者lxml有时难以安装:

http://etienned.github.io/posts/extract-text-from-word-docx-simply/

于 2017-08-16T04:32:55.060 回答
8

python-docx 有两个“世代”。最初的一代以 0.2.x 版本结束,“新”一代从 v0.3.0 开始。新一代是对旧版本的全新、面向对象的重写。它有一个独特的存储库,位于此处

opendocx() 函数是遗留 API 的一部分。该文档适用于新版本。旧版没有文档可言。

当前版本不支持读写超链接。该功能已在路线图上,并且该项目正在积极开发中。事实证明它是一个相当广泛的 API,因为 Word 具有如此多的功能。所以我们会着手解决,但可能不会在下个月,除非有人决定专注于这方面并做出贡献。 在此答案之后添加了更新超链接支持。

于 2014-08-10T19:50:16.903 回答
4

使用 python-docx,正如@Chinmoy Panda 的回答所示:

for para in doc.paragraphs:
    fullText.append(para.text)

但是,para.text 会丢失文本w:smarttag(对应的 github 问题在这里:https://github.com/python-openxml/python-docx/issues/328),您应该改用以下函数:

def para2text(p):
    rs = p._element.xpath('.//w:t')
    return u" ".join([r.text for r in rs])
于 2018-06-06T05:40:01.953 回答
0

我遇到了类似的问题,所以我找到了一种解决方法(通过正则表达式删除超链接标签,以便只保留一个段落标签)。我在https://github.com/python-openxml/python-docx/issues/85 BP上发布了这个解决方案

于 2014-11-18T07:09:08.573 回答
0

这个问题似乎没有官方解决方案,但是这里发布了一个解决方法 https://github.com/savoirfairelinux/python-docx/commit/afd9fef6b2636c196761e5ed34eb05908e582649

只需更新此文件“...\site-packages\docx\oxml_init _.py

# add
import re
import sys

# add
def remove_hyperlink_tags(xml):
    if (sys.version_info > (3, 0)):
        xml = xml.decode('utf-8')
    xml = xml.replace('</w:hyperlink>', '')
    xml = re.sub('<w:hyperlink[^>]*>', '', xml)
    if (sys.version_info > (3, 0)):
        xml = xml.encode('utf-8')
    return xml
    
# update
def parse_xml(xml):
    """
    Return root lxml element obtained by parsing XML character string in
    *xml*, which can be either a Python 2.x string or unicode. The custom
    parser is used, so custom element classes are produced for elements in
    *xml* that have them.
    """
    root_element = etree.fromstring(remove_hyperlink_tags(xml), oxml_parser)
    return root_element

当然不要忘记在文档中提到使用正在更改官方库

于 2021-02-17T08:59:01.020 回答