【问题标题】:Parsing of table from .docx file [closed]从.docx文件解析表[关闭]
【发布时间】:2015-01-09 13:32:33
【问题描述】:

我想使用 Python 和 python-docx 将 .docx 文件中的表解析为一些有用的数据结构。

在我的例子中,.docx 文件只包含一个表。我有uploaded it so you can have a look。截图如下:

【问题讨论】:

  • 邮政编码和相关材料在此,不在某些第三方网站上,尤其是在某些未知网站的短网址上。
  • 我已经尝试了很多方法来解析它,但是没有得到任何工作——所以没有粘贴代码。如果代码不工作,我认为它没有用
  • @Cyber​​ 我已在该链接中附加了 docx 文件 - 除了这个

标签: python xml parsing docx python-docx


【解决方案1】:

您可以使用下面的 sn-p 将您的文档解析为一个列表,其中每一行都是一个字典,将表头值映射到列值。

from docx.api import Document

# Load the first table from your document. In your example file,
# there is only one table, so I just grab the first one.
document = Document('Books.docx')
table = document.tables[0]

# Data will be a list of rows represented as dictionaries
# containing each row's data.
data = []

keys = None
for i, row in enumerate(table.rows):
    text = (cell.text for cell in row.cells)

    # Establish the mapping based on the first row
    # headers; these will become the keys of our dictionary
    if i == 0:
        keys = tuple(text)
        continue

    # Construct a dictionary for this row, mapping
    # keys to values for this row
    row_data = dict(zip(keys, text))
    data.append(row_data)

这会给你:

data = [
  {u'Pub.': u'Penguin Books',
   u'Auther': u'Edward de BONO',
   u'Sr. No.': u'1',
   u'Name of Book': u'Six Thinking Hats'
  },
  ...
]

如果您只想为每一行创建一个元组,则不应创建字典,只需将row_data 设置为text 的元组值,因此在循环中而不是构造dict,请执行以下操作:

# Construct a tuple for this row
row_data = tuple(text)
data.append(row_data)

现在,data 将持有这样的东西:

data = [
  (u'1',
   u'Six Thinking Hats',
   u'Edward de BONO',
   u'Penguin Books'
  ),
 ...
]

那么您显然可以跳过构造keys(但仍然跳过第一行!)。

【讨论】:

  • 除此之外,如果docx.api 抛出错误,那么如果您安装的库是python-docx 而不是docx,则可以直接使用from docx import Document。 Python-docx 兼容 python2.x 和 3.x
猜你喜欢
  • 1970-01-01
  • 2012-05-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-12
  • 1970-01-01
相关资源
最近更新 更多