我需要通过关键字查找单元格并显示相邻单元格的信息。我只需要显示一个数字。我该怎么做?
这里我必须手动插入表格、行号和行号。但我想自动化这个。 如何通过关键字自动搜索页面、行和列?
import re
from docx import Document
document = Document('889411.docx')
table_apartments = document.tables[37] #<--- The page number needs to be automatically substituted
cell_apartments = table_apartments.cell(10, 2) #<---- I need to automatically insert the row and column
num_of_apartments = re.findall("\d+", cell_apartments.text)[0]#<---Here I remove the text leaving the numbers
print(num_of_apartments)
你想要通过关键字搜索 Word 文档中的表格,找到包含关键字的单元格,并返回该单元格同一行中指定列的数字。
以下代码展示了如何实现这一点:
import re
from docx import Document
def find_cell_by_keyword(table, keyword):
"""在表格中查找包含指定关键字的单元格。
Args:
table: 要搜索的表格对象。
keyword: 要查找的关键字。
Returns:
包含关键字的单元格对象,如果没有找到则返回 None。
"""
for row in table.rows:
for cell in row.cells:
if keyword in cell.text:
return cell
return None
def extract_number_from_cell(cell, column_index):
"""从指定单元格的同一行中提取指定列的数字。
Args:
cell: 包含关键字的单元格对象。
column_index: 要提取数字的列索引(从 0 开始)。
Returns:
提取到的数字,如果没有找到则返回 None。
"""
row = cell.row
if 0 <= column_index < len(row.cells):
target_cell = row.cells[column_index]
match = re.findall(r'\d+', target_cell.text)
if match:
return int(match[0])
return None
# 加载 Word 文档
document = Document('889411.docx')
# 设置要查找的关键字、目标列索引和表格索引
keyword = "公寓数量" # 例如,要查找包含“公寓数量”的单元格
target_column_index = 2 # 例如,要提取第三列的数字
table_index = 37 # 例如,要搜索第 38 个表格
# 获取目标表格
table = document.tables[table_index]
# 查找包含关键字的单元格
cell = find_cell_by_keyword(table, keyword)
if cell:
# 提取数字
number = extract_number_from_cell(cell, target_column_index)
if number:
print(f"找到的数字: {number}")
else:
print("在指定列中未找到数字。")
else:
print(f"未找到包含关键字 '{keyword}' 的单元格。")
代码说明:
-
find_cell_by_keyword(table, keyword)
函数:- 遍历表格中的每个单元格。
- 如果单元格文本包含指定的关键字,则返回该单元格对象。
-
如果没有找到,则返回
None
。
-
extract_number_from_cell(cell, column_index)
函数:- 获取包含关键字的单元格所在的行。
- 检查指定的列索引是否有效。
- 如果有效,则获取该行中指定列的单元格。
- 使用正则表达式从单元格文本中提取数字。
- 如果找到数字,则将其转换为整数并返回。
-
如果没有找到,则返回
None
。
-
主程序:
- 设置要查找的关键字、目标列索引和表格索引。
-
调用
find_cell_by_keyword
函数查找包含关键字的单元格。 -
如果找到单元格,则调用
extract_number_from_cell
函数提取数字并打印结果。 - 如果没有找到单元格或数字,则打印相应的提示信息。
使用方法:
-
将代码保存为 Python 文件(例如,
extract_data.py
)。 -
将
keyword
、target_column_index
和table_index
变量的值替换为你自己的值。 -
运行代码:
python extract_data.py
这将打印从 Word 文档中提取的数字。
标签:python,docx From: 78810381