首页 > 编程问答 >如何在更改代码时自动运行代码?

如何在更改代码时自动运行代码?

时间:2024-08-01 08:18:47浏览次数:6  
标签:python api automation google-gemini

我有以下代码,它使用 google gemini api 处理名为“pdf_texts_79_batch_#.txt”的文件。文件名中的“#”代表一个从 1 开始并依次递增的数字。我需要这样做,以便我可以运行代码,然后我可以将文件名中的数字更改为 onqecutive 数字,然后再次运行代码,所有这些都是自主的。例如,我的代码如下所示:

import google.generativeai as genai
import os

gemini_key = "ABCDEFG123456789"

genai.configure(api_key=gemini_key)

with open('pdf_texts_79_batch_1.txt', 'r', encoding='utf-8') as file:
    input_text = file.read()

model = genai.GenerativeModel(model_name="gemini-1.5-pro")
response = model.generate_content([
    """
Get rid of all instances of the letter "t".
""" + input_text
])

with open('extract-sections.txt', 'w', encoding='utf-8') as output_file:
    output_file.write(response.text)

print("Output has been saved to extract-sections.txt")

运行该代码一次后,我会将“pdf_texts_79_batch_1.txt”更改为“pdf_texts_79_batch_2.t​​xt”并再次运行该代码。由于 Gemini api 的令牌限制,我无法合并我的 txt 文件。

我尝试合并我的 txt 文件,但后来遇到了字符限制问题。通过字符限制的唯一方法是付费,但这很快就会变得非常昂贵。


你可以使用循环和字符串格式化来实现这个目标。以下是如何修改你的代码:

import google.generativeai as genai
import os

gemini_key = "ABCDEFG123456789"
genai.configure(api_key=gemini_key)

# 设置起始批次号
batch_start = 1
# 设置结束批次号
batch_end = 10 

model = genai.GenerativeModel(model_name="gemini-1.5-pro")

# 循环遍历所有批次
for batch_num in range(batch_start, batch_end + 1):
    # 使用字符串格式化构建文件名
    input_filename = f"pdf_texts_79_batch_{batch_num}.txt"

    # 检查文件是否存在
    if not os.path.exists(input_filename):
        print(f"文件 {input_filename} 不存在,跳过。")
        continue

    with open(input_filename, 'r', encoding='utf-8') as file:
        input_text = file.read()

    response = model.generate_content([
        """
    Get rid of all instances of the letter "t".
    """ + input_text
    ])

    output_filename = f"extract-sections_batch_{batch_num}.txt"
    with open(output_filename, 'w', encoding='utf-8') as output_file:
        output_file.write(response.text)

    print(f"批次 {batch_num} 的输出已保存到 {output_filename}")

print("所有批次处理完毕。")

这段代码做了以下几件事:

  1. 使用循环处理多个文件: 它使用 for 循环来迭代批次号,从 batch_start batch_end
  2. 使用字符串格式化构建文件名: 它使用 f-string 来动态地创建文件名,例如 pdf_texts_79_batch_1.txt , pdf_texts_79_batch_2.txt 等。
  3. 检查文件是否存在: 在尝试打开文件之前,它使用 os.path.exists() 检查文件是否存在。如果文件不存在,它会打印一条消息并跳过该文件。
  4. 为每个批次创建单独的输出文件: 它使用与输入文件名类似的格式为每个批次创建一个单独的输出文件,例如 extract-sections_batch_1.txt , extract-sections_batch_2.txt 等。

要使用这段代码,你需要:

  1. 设置 batch_start batch_end 变量: batch_start 设置为第一个批次的编号,将 batch_end 设置为最后一个批次的编号。
  2. 确保所有输入文件都存在: 确保所有名为 pdf_texts_79_batch_#.txt 的文件都存在于你的工作目录中,其中 # 是从 batch_start batch_end 的数字。

运行这段代码后,它会自动处理所有批次的文件,并将每个批次的输出保存到一个单独的文件中。

标签:python,api,automation,google-gemini
From: 78818668

相关文章

  • ffmpeg python 导致死锁
    我在使用ffmpegpython处理相机帧时遇到问题。我使用process.communicate()的第一种方法效果很好,但存在延迟问题。process=(ffmpeg.input('pipe:',format='rawvideo',pix_fmt='rgb24',s='{}x{}'.format(width,height))......
  • 将 HTTP 分块编码数据流代码片段从 Node.js 转换为 Python
    我有一个Node.js客户端代码,它将请求发送到HTTP服务器,然后连续接收分块编码数据。这是带有一些流量数据输出的Node.js代码。consthttp=require('http');constoptions={hostname:'...',path:'...',port:...,...};constreq=http.request(......
  • Google Translate API 客户端没有“Translate_image”属性
    importosfromgoogle.cloudimporttranslate_v3beta1astranslatedefupload_and_translate(input_dir,output_dir,target_language):"""Uploadsallimagesinadirectory,translatesthemusingGoogleTranslate,anddownloadsthetrans......
  • vsc python 调试器和 pylance 无法识别已安装的包
    我最近使用snowflake-connector-python在我的虚拟环境中安装了pipinstallsnowflake-connector-python[pandas]==2.7.6,当我在激活虚拟环境的情况下从命令行运行我的脚本时,它工作正常。我设置了与VSC解释器相同的虚拟环境,但尝试运行python调试器会引发异常......
  • 如何从python读取matlab持续时间对象
    我创建一个matlab持续时间对象并将其保存到.mat文件:timeend=seconds(123);save('time.mat',timeend,'-v7.3');然后我从python读取它:withh5py.File('time.mat','r')asf:var=f['timeend'][:]print(list(var))......
  • 通过 python 连接到 Snowflake 时出错“UnpicklingError: invalid load key, '\x00'
    我在使用snowflake.connector.connect通过python连接到snowflake时遇到以下错误importsnowflake.connector#pipinstallsnowflake-connector-python#iamgettingtheenvfrom.envfileistoredlocallycnx=snowflake.connector.connect(user=os.getenv('USER'),pass......
  • Python Selenium 单击 webdriverwait 与 find_element
    我无法理解这两个代码块之间的区别。发送点击在webdriverwait和find_elements中都有效。代码1fromseleniumimportwebdriverfromselenium.webdriver.common.byimportByfromselenium.webdriver.support.uiimportWebDriverWaitfromselenium.webdriver.suppo......
  • Python 问题 如何创建在 PDF 中注册为剪切线的专色?
    我正在开发一个项目,需要我在图像周围创建一条剪切线,但在任何RIP程序(例如Versaworks或Flexi)上将其注册为实际剪切线时遇到困难。我尝试了很多不同的方法python库可以帮助解决这个问题,但我无法让它工作。我希望它像我们在Illustrator中所做的那样,创建一条名为CutConto......
  • 使用Python时如何避免`setattr`(和`getattr`)?以及是否有必要避免
    如果我想向协议缓冲区中的字段添加一个在编译时未知的值,我目前正在做setattr我通常不喜欢使用setattr,因为它看起来不太安全。但是当我知道该对象是protobuf时,我认为这很好,因为我设置它的值必须是protobuf允许的类型。所以也许它并不是真的不安全?让我举......
  • Java sshtools 生成的 EDDSA 签名与 Python 的 pycryptome 生成的签名不匹配
    我有一个python库,它使用pycryptodomelibrary使用openssh格式的ED25519私钥使用Ed25519算法对数据进行签名。然后需要使用sshtools库和相应的公钥在Java应用程序中验证签名。但是签名验证失败。约束:从文件中读取私钥/公钥很重要。我无法......