使用 docx 解析字典格式的 table 数据
Parsing a table data in dictionary format using docx
我正在尝试使用 Python docx 模块解析一组特定的 table 数据。
table 数据看起来像这样
我需要以键值格式检索 "Authorities" 和相应的 "Versions",以便我可以使用该数据进行进一步处理。
如果我使用 -
,我将无法遍历字典
d = OrderedDict(zip(table.cell(rowNo, 0).text, table.cell(rowNo, 2).text))
这给了我 orderedDictionary 但我无法使用 d['Juno']
访问这些值
我希望给我 4.5.6
from docx import Document
document = Document('myfile.docx')
for table in document.tables:
printTable = False
rowNo = 0;
for row in table.rows:
for cell in row.cells:
if cell.text == "Table2":
printTable = False
if printTable:
print (table.cell(rowNo, 0).text + '=' + table.cell(rowNo, 2).text)
for cell in row.cells:
if cell.text == "Authorities":
printTable = True
rowNo += 1
解析后我得到以下格式的数据 -
Juno=4.5.6
Acrux=3.5.6
Mars=5.6.7
你可以定义一个字典并实现这个 -
from docx import Document
document = Document('myfile.docx')
data = {}
for table in document.tables:
printTable = False
rowNo = 0;
for row in table.rows:
for cell in row.cells:
if cell.text == "Table2":
printTable = False
if printTable:
data[table.cell(rowNo, 0).text] = table.cell(rowNo, 2).text
for cell in row.cells:
if cell.text == "Authorities":
printTable = True
rowNo += 1
print (data)
将为您提供字典格式的预期数据
我正在尝试使用 Python docx 模块解析一组特定的 table 数据。
table 数据看起来像这样
我需要以键值格式检索 "Authorities" 和相应的 "Versions",以便我可以使用该数据进行进一步处理。
如果我使用 -
,我将无法遍历字典d = OrderedDict(zip(table.cell(rowNo, 0).text, table.cell(rowNo, 2).text))
这给了我 orderedDictionary 但我无法使用 d['Juno']
访问这些值
我希望给我 4.5.6
from docx import Document
document = Document('myfile.docx')
for table in document.tables:
printTable = False
rowNo = 0;
for row in table.rows:
for cell in row.cells:
if cell.text == "Table2":
printTable = False
if printTable:
print (table.cell(rowNo, 0).text + '=' + table.cell(rowNo, 2).text)
for cell in row.cells:
if cell.text == "Authorities":
printTable = True
rowNo += 1
解析后我得到以下格式的数据 -
Juno=4.5.6
Acrux=3.5.6
Mars=5.6.7
你可以定义一个字典并实现这个 -
from docx import Document
document = Document('myfile.docx')
data = {}
for table in document.tables:
printTable = False
rowNo = 0;
for row in table.rows:
for cell in row.cells:
if cell.text == "Table2":
printTable = False
if printTable:
data[table.cell(rowNo, 0).text] = table.cell(rowNo, 2).text
for cell in row.cells:
if cell.text == "Authorities":
printTable = True
rowNo += 1
print (data)
将为您提供字典格式的预期数据