You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Python代码批量提取指定数据并存入列表(禁用正则)

批量提取任务的Python代码修改方案

以下是针对你需求的代码修改,实现批量处理两个提取任务,且未使用正则或extract类函数:

任务1:提取TXT每行第一个括号内的数字

封装函数批量读取文件并提取:

def extract_first_bracket_number(file_path):
    result = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue  # 跳过空行
            # 定位第一个括号的起止位置
            start_idx = line.find("(") + 1
            end_idx = line.find(")", start_idx)
            if start_idx > 0 and end_idx > start_idx:
                num_str = line[start_idx:end_idx]
                result.append(int(num_str))
    return result

任务2:批量读取时间字符串到列表

同样通过文件读取实现批量收集:

def extract_time_strings(file_path):
    result = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            time_str = line.strip()
            if time_str:  # 跳过空行
                result.append(time_str)
    return result

整合到现有代码的完整实现

替换原有单条输入逻辑,将批量提取结果写入Excel:

import pyautogui, time
from datetime import date
import openpyxl

def extract_first_bracket_number(file_path):
    result = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            line = line.strip()
            if not line:
                continue
            start_idx = line.find("(") + 1
            end_idx = line.find(")", start_idx)
            if start_idx > 0 and end_idx > start_idx:
                num_str = line[start_idx:end_idx]
                result.append(int(num_str))
    return result

def extract_time_strings(file_path):
    result = []
    with open(file_path, 'r', encoding='utf-8') as f:
        for line in f:
            time_str = line.strip()
            if time_str:
                result.append(time_str)
    return result

# 主逻辑
row = 1
wb = openpyxl.load_workbook("data.xlsx")
ws = wb['Sheet1']
today = date.today()
Cyear = str(today.year)

# 处理任务1:替换为你的数字文件路径
num_file = "numbers.txt"
XQ = extract_first_bracket_number(num_file)
# 将提取的数字写入Excel A列
for idx, num in enumerate(XQ, start=1):
    ws.cell(row=idx, column=1, value=num)

# 处理任务2:替换为你的时间文件路径
time_file = "times.txt"
time_list = extract_time_strings(time_file)
# 将时间字符串(拼接年份后)写入Excel B列
for idx, time_str in enumerate(time_list, start=1):
    ws.cell(row=idx, column=2, value=f"{Cyear}-{time_str}")

# 保存修改后的Excel
wb.save("data.xlsx")

使用说明

  1. 将需要处理的数字行保存为numbers.txt,每行格式如4(12)(52.17%);
  2. 将时间字符串保存为times.txt,每行格式如06-23 16:15;
  3. 修改代码中的文件路径为实际路径;
  4. 运行代码后,提取结果会写入data.xlsx的A、B列。

内容的提问来源于stack exchange,提问作者Momoko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 01:12:23