如何自动运行代码批量处理递增编号的Gemini API输入文件
自动遍历处理编号批量TXT文件(适配Google Gemini API)
直接通过循环递增文件编号的方式,自动逐个处理所有pdf_texts_79_batch_#.txt文件,无需手动修改文件名。同时为避免输出文件被覆盖,每个批次的处理结果会保存为独立的输出文件。
修改后的完整代码
import google.generativeai as genai import os gemini_key = "ABCDEFG123456789" genai.configure(api_key=gemini_key) batch_num = 1 prompt = """Get rid of all instances of the letter "t".""" while True: input_filename = f'pdf_texts_79_batch_{batch_num}.txt' # 检查文件是否存在,不存在则终止循环 if not os.path.exists(input_filename): print(f"未找到文件 {input_filename},批量处理结束") break # 读取输入文件 try: with open(input_filename, 'r', encoding='utf-8') as file: input_text = file.read() except Exception as e: print(f"读取文件 {input_filename} 失败:{str(e)}") batch_num += 1 continue # 调用Gemini API处理文本 try: model = genai.GenerativeModel(model_name="gemini-1.5-pro") response = model.generate_content([prompt + input_text]) # 确保API返回有效内容 if not hasattr(response, 'text') or response.text is None: print(f"处理文件 {input_filename} 时API未返回有效内容") batch_num += 1 continue except Exception as e: print(f"调用Gemini API处理文件 {input_filename} 失败:{str(e)}") batch_num += 1 continue # 保存输出结果(每个批次对应独立文件) output_filename = f'extract-sections_{batch_num}.txt' try: with open(output_filename, 'w', encoding='utf-8') as output_file: output_file.write(response.text) print(f"文件 {input_filename} 处理完成,结果已保存到 {output_filename}") except Exception as e: print(f"保存文件 {output_filename} 失败:{str(e)}") batch_num += 1
关键逻辑说明
- 自动遍历机制:从
batch_num=1开始,每次循环递增编号,通过os.path.exists()检查对应文件是否存在,不存在则终止循环,无需手动指定总批次数量。 - 独立输出文件:将输出文件名改为
extract-sections_{batch_num}.txt,避免不同批次的处理结果互相覆盖。 - 异常捕获:针对文件读取、API调用、文件保存三个环节添加异常捕获,确保单个文件处理失败时,整个批量任务不会中断,继续处理下一个文件。
- Prompt分离:将固定Prompt单独提取,提升代码可读性,便于后续修改。
注意事项
- 确保Google Gemini API密钥有效,且账户有足够的Token额度(避免因Token耗尽导致批量任务中断)。
- 若API存在速率限制,可在循环中添加
time.sleep()控制请求间隔,避免触发限流。 - 确认所有批量TXT文件与代码在同一目录下,或修改
input_filename为完整文件路径。
内容的提问来源于stack exchange,提问作者Shriyan Yamali
相关产品推荐
相关产品推荐

