首页 > 编程问答 >如何通过关键字显示这些信息?

如何通过关键字显示这些信息?

时间:2024-07-30 15:52:07浏览次数:7  
标签:python docx

我需要通过关键字查找单元格并显示相邻单元格的信息。我只需要显示一个数字。我该怎么做?

这里我必须手动插入表格、行号和行号。但我想自动化这个。 如何通过关键字自动搜索页面、行和列?

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}' 的单元格。")

代码说明:

  1. find_cell_by_keyword(table, keyword) 函数:
    • 遍历表格中的每个单元格。
    • 如果单元格文本包含指定的关键字,则返回该单元格对象。
    • 如果没有找到,则返回 None
  2. extract_number_from_cell(cell, column_index) 函数:
    • 获取包含关键字的单元格所在的行。
    • 检查指定的列索引是否有效。
    • 如果有效,则获取该行中指定列的单元格。
    • 使用正则表达式从单元格文本中提取数字。
    • 如果找到数字,则将其转换为整数并返回。
    • 如果没有找到,则返回 None
  3. 主程序:
    • 设置要查找的关键字、目标列索引和表格索引。
    • 调用 find_cell_by_keyword 函数查找包含关键字的单元格。
    • 如果找到单元格,则调用 extract_number_from_cell 函数提取数字并打印结果。
    • 如果没有找到单元格或数字,则打印相应的提示信息。

使用方法:

  1. 将代码保存为 Python 文件(例如, extract_data.py )。
  2. keyword target_column_index table_index 变量的值替换为你自己的值。
  3. 运行代码: python extract_data.py

这将打印从 Word 文档中提取的数字。

标签:python,docx
From: 78810381

相关文章

  • 使用python从网站自动下载pdf时出错
    我想从一个名为epadossier.nl的网站自动批量下载pdf我用谷歌搜索了这个并找到了一段代码并修复了一个小错误。所以现在我得到了这个`importrequestsurl="https://www.epadossier.nl/adres/plaats/straat/num"response=requests.get(url)ifresponse.status_cod......
  • 避免字符串连接的嵌套循环的 Pythonic 方法
    我想找到所有5位数字的字符串,其中前三位数字在我的第一个列表中,第二个槽第四个数字在我的第二个列表中,第三到第五个数字在我的最后一个列表中:l0=["123","567","451"]l1=["234","239","881"]l2=["348","551","399"......
  • Python 环境配置(二)安装jupyter、matplotlib、numpy库
    Python环境配置(二)安装jupyter、matplotlib、numpy库一、numpypipinstallnumpy二、matplotlibpipinstallmatplotlib三、jupyter1、anaconda自带Jupyter2、pycharm插件只有Pycharm的Professional版才支持JupyterNotebook,请注意版本3、新建文件#%......
  • 如何使用 PIPE 并行运行 python 子进程?
    我正在使用inkscape将一堆SVG图像转换为PNG。单线程:importsubprocessimporttimeimportosinkscape_path=r'C:\ProgramFiles\Inkscape\bin\inkscape.com'steps=30filenames=[]processes=[]#t_start=time.process_time()t_start=time.time()f......
  • Python sqlite3 删除数据
    要从SQLite表中删除记录,你需要使用DELETEFROM语句。要删除特定的记录,你需要同时使用WHERE子句。要更新特定的记录,你需要同时使用WHERE子句。语法以下是SQLite中DELETE查询的语法- DELETEFROMtable_name[WHEREClause]PythonCopy例子假设我们使用以下查询创建了......
  • Python 环境配置(一)Python、Anaconda、Pycharm的安装
    Python环境配置(一)Python、Anaconda、Pycharm的安装本人之前已安装一次,此次为卸载之后的重新安装。。。一、Python1、下载下载官网:下载链接:DownloadPython|Python.org勾选添加到路径(环境变量)next如图所示之后点close关闭2、验证win+Rcmd:python退出ex......
  • Pycharm 设置 yaml 格式接口测试用例模板 (python+pytest+yaml)
    前言初次编写的伙伴们可能对yaml格式不太熟悉,自己写yaml用例的时候,总是格式对不齐啊记不住设定好的关键字啊等等等琐事是我们可以在pycharm上设置用例模块,通过快捷方式调用出对应的模块,达到高效写用例的目的。 pycharm操作集:1、File-Settings(快捷键Ctrl+Alt+S) 2、Live......
  • Python - Redirecting output of print to a file
    Theprintfunctioncanalsobeusedtowritetoafile.Theoutputofprint,thatisbydefault,senttothescreencanberedirectedtoanopenfile.Forthis,youhavetosupplythefileobjectasanargumentforthenamedparameterfile.Hereisanexa......
  • Python:添加到相对于当前运行脚本的 sys.path 的最佳方法
    我有一个充满脚本的目录(比如说project/bin)。我还有一个位于project/lib的库,并希望脚本自动加载它。这是我通常在每个脚本的顶部使用的:#!/usr/bin/pythonfromos.pathimportdirname,realpath,sep,pardirimportsyssys.path.append(dirname(realpath(_......
  • python身份证号码+姓名一致性核验、身份证号码真伪查询API集成
    身份证号码+姓名核验的方式,顾名思义是身份证二要素核验,一般情况下,身份证真伪查询需要上公安户籍系统查询,但此种方式仅适合个人查询,企业要想随时随地实现身份证实名认证的功能,便需要集成身份证实名认证接口功能。翔云人工智能开放平台提供身份证号实名认证接口,实时联网,上传身份证......