python -docx 从 word docx 中提取 table

python -docx to extract table from word docx

我知道这是一个重复的问题,但其他答案对我不起作用。 我有一个包含一个 table 的 word 文件。我希望 table 作为我的 python 程序的输出。我正在使用 python 3.6 并且我也安装了 python -docx。这是我的数据提取代码

from docx.api import Document

document = Document('test_word.docx')
table = document.tables[0]

data = []

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

    if i == 0:
        keys = tuple(text)
        continue
    row_data = dict(zip(keys, text))
    data.append(row_data)
    print (data)

我想要与 word docx 文件完全一样的结果。提前致谢

你的代码对我来说工作正常。将它插入数据框怎么样?

import pandas as pd
from docx.api import Document

document = Document('test_word.docx')
table = document.tables[0]

data = []

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

    if i == 0:
        keys = tuple(text)
        continue
    row_data = dict(zip(keys, text))
    data.append(row_data)
    print (data)

df = pd.DataFrame(data)

如何在 table 中显示特定的行和列? 我们可以使用 iloc

基于索引提取行和列
# iloc[row,columns] 
df.iloc[0,:].tolist() # [5,6,7,8]  - row index 0
df.iloc[:,0].tolist() # [5,9,13,17]  - column index 0
df.iloc[0,0] # 5  - cell(0,0)
df.iloc[1:,2].tolist() # [11,15,19]  - column index 2, but skip first row

等等...

但是,如果您的列有名称(在本例中是数字),您可以这样做:

#df["name"].tolist() 
df[1].tolist() # [5,6,7,8] - column with name 1 

print(df)

打印,这就是 table 在我的示例文档中的样子。

    1   2   3   4
0   5   6   7   8
1   9   10  11  12
2   13  14  15  16
3   17  18  19  20