【问题标题】:How to extract text from a table in a .docx file?如何从 .docx 文件中的表格中提取文本?
【发布时间】:2018-08-13 02:26:02
【问题描述】:

我想使用 python 从 .docx 文件中的表中提取文本以进行进一步分析。我使用以下代码:

document = Document(path_to_your_docx)
tables = document.tables
for table in tables:
    for row in table.rows:
        for cell in row.cells:
            for paragraph in cell.paragraphs:
                print(paragraph.text)

但是这个表格的单元格中似乎还有另一个“表格”,所以我无法提取这部分(如附图所示)。当我使用上面的代码时,我无法获取“是/否”文本。

我也尝试像在表格中一样遍历单元格,但我收到单元格没有表格属性的错误。有什么建议吗?

The table looks like this

code behind table creation

谢谢。

【问题讨论】:

  • 请勿粘贴代码截图。

标签: python docx python-docx


【解决方案1】:

我有解决此问题的方法。我没有使用库 python-docx 从 docx 文件中提取文本,而是使用库 docx2txt (提取 all 文本)和那么我只需要在字符串中找到特定的单词。

text = docx2txt.process(file)

q = "Example1"
result = text[text.find(q)+len(q):].split()[0]

这给了我来自 Column2 的“是”或“否”,对于 Column1 上的每个值(在上面的示例中,它给出 Yes)。

【讨论】:

  • 可行,但 docx2python 会提取表格。该嵌套表需要一些后期处理,但文档中清楚地描述了输出。
猜你喜欢
  • 2014-02-05
  • 2014-10-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多