gpt4 book ai didi

python - 在 Word 表格中搜索特定文本 Python docx

转载 作者:太空宇宙 更新时间:2023-11-04 00:27:23 27 4
gpt4 key购买 nike

我有一些代码可以读取 Word 文档中的表格并从中制作数据框。

import numpy as np
import pandas as pd
from docx import Document

#### Time for some old fashioned user functions ####
def make_dataframe(f_name, table_loc):
document = Document(f_name)
tables = document.tables[table_loc]

for i, row in enumerate(tables.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)
df = pd.DataFrame.from_dict(data)
return df


SHRD_filename = "SHRD - 12485.docx"
SHDD_filename = "SHDD - 12485.docx"

df_SHRD = make_dataframe(SHRD_filename,30)
df_SHDD = make_dataframe(SHDD_filename,-60)

因为文件不一样(比如SHRD有32张表,我要找的是倒数第二张,而SHDD文件有280张表,我要找的是倒数第60张。但情况可能并非总是如此。

如何搜索文档中的表格并开始处理 cell[0,0] = 'Tag Numbers' 的表格。

最佳答案

您可以遍历表格并检查第一个单元格中的文本。我修改了输出以返回数据帧列表,以防万一找到多个表。如果没有表符合条件,它将返回一个空列表。

def make_dataframe(f_name, first_cell_string='tag number'):
document = Document(f_name)

# create a list of all of the table object with text of the
# first cell equal to `first_cell_string`
tables = [t for t in document.tables
if t.cell(0,0).text.lower().strip()==first_cell_string]

# in the case that more than one table is found
out = []
for table in tables:
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)
out.append(pd.DataFrame.from_dict(data))
return out

关于python - 在 Word 表格中搜索特定文本 Python docx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46992168/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com