python-docx: 查找ms word文档中table所在的标题名称
python-docx: Find the heading name in which a table lies inside a ms word document
我正在努力寻找 table 所在的标题名称,我正在使用 python-docx 库,我想知道我可以用来获取 table 沿其位于其中的标题名称。
from docx import Document
from docx.shared import Inches
document = Document('test.docx')
tabs = document.tables
您可以使用 xml 从 docx 文件中提取结构化信息。试试这个:
doc = Document("file.docx")
headings = [] #extract only headings from your code
tables = [] #extract tables from your code
tags = []
all_text = []
schema = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
for elem in doc.element.getiterator():
if elem.tag == schema + 'body':
for i, child in enumerate(elem.getchildren()):
if child.tag != schema + 'tbl':
node_text = child.text
if node_text:
if node_text in headings:
tags.append('heading')
else:
tags.append('text')
all_text.append(node_text)
else:
tags.append('table')
break
在上面的代码之后,您将获得显示文档标题、文本和table结构的标签列表,然后您可以映射列表中的相应数据。
同时检查标签列表中的数据以获取 table 的标题。
我正在努力寻找 table 所在的标题名称,我正在使用 python-docx 库,我想知道我可以用来获取 table 沿其位于其中的标题名称。
from docx import Document
from docx.shared import Inches
document = Document('test.docx')
tabs = document.tables
您可以使用 xml 从 docx 文件中提取结构化信息。试试这个:
doc = Document("file.docx")
headings = [] #extract only headings from your code
tables = [] #extract tables from your code
tags = []
all_text = []
schema = '{http://schemas.openxmlformats.org/wordprocessingml/2006/main}'
for elem in doc.element.getiterator():
if elem.tag == schema + 'body':
for i, child in enumerate(elem.getchildren()):
if child.tag != schema + 'tbl':
node_text = child.text
if node_text:
if node_text in headings:
tags.append('heading')
else:
tags.append('text')
all_text.append(node_text)
else:
tags.append('table')
break
在上面的代码之后,您将获得显示文档标题、文本和table结构的标签列表,然后您可以映射列表中的相应数据。
同时检查标签列表中的数据以获取 table 的标题。