python-docx: Parse a table to Panda Dataframe

≯℡__Kan透↙ 提交于 2020-05-17 08:30:26

问题


I'm using the python-docx library to extract ms word document. I'm able to get all the tables from the word document by using the same library. However, I'd like to parse the table into a panda data frame, is there any built-in functionality I can use to parse the table into data frame or I'll have to do it manually? Also, is there a possibility to know the heading name in which the table lies inside? Thank you

from docx import Document
from docx.shared import Inches
document = Document('test.docx')

tabs = document.tables

回答1:


You can extract tables from the document in data-frame by using this code :

from docx import Document
import pandas as pd
document = Document('test.docx')

tables = []
for table in document.tables:
    df = [['' for i in range(len(table.columns))] for j in range(len(table.rows))]
    for i, row in enumerate(table.rows):
        for j, cell in enumerate(row.cells):
            if cell.text:
                df[i][j] = cell.text
    tables.append(pd.DataFrame(df))
print(tables)

You can get all the tables from the tables variable.



来源:https://stackoverflow.com/questions/58254609/python-docx-parse-a-table-to-panda-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!