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
A similar alternative (but I did not test using multiple tables).
This gave me the dataframe format I was looking for:
for table in firstdoc.tables:
doctbls=[]
tbllist=[]
rowlist=[]
for i, row in enumerate(table.rows):
for j, cell in enumerate(row.cells):
rowlist.append(cell.text)
tbllist.append(rowlist)
rowlist=[]
doctbls=doctbls+tbllist
finaltables=pd.DataFrame(doctbls)
display(finaltables)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With