首先,在阿里云的dashScope灵积模型服务中,申请一个API-key,有挺多免费token的。

然后,在通义千问中输入提示词:

你是一个Python编程专家,现在要完成一个编写基于qwen-turbo模型API和dashscope库的程序脚本,具体步骤如下:

打开文件夹:D:\AR

获取里面所有的txt文档;

读取txt文件内容;

将每个txt文件的内容作为输入,并在调用API时附加提示语“翻译成中文”,API Key为:XXX ,model为qwen-turbo;

接收API返回的结果,并将其保存到在同一文件夹中,文件标题名为原txt文件标题名加上“总结”,文档格式为txt文档;

注意:

每一步都要打印相关的信息;

根据API的限流和请求要求,合理安排任务的发送频率,避免触发API的速率限制;

要有错误处理和调试信息,这有助于找出问题所在;

请求的输入长度范围应当在[1, 6000]之间,如果超长,需要对TXT内容进行截断,使其不超过6000个字符,然后再发送至API。

在读取文件时跳过那些以"_总结.txt"结尾的文件,避免递归地处理同一个文件夹下的所有文件,包括已经生成的总结文件。

qwen-turbo模型API的使用方法,请参照下面这个例子:

from http import HTTPStatus

import dashscope

def sample_sync_call():

prompt_text = '用萝卜、土豆、茄子做饭,给我个菜谱。'

resp = dashscope.Generation.call(

model='qwen-turbo',

prompt=prompt_text

)

# The response status_code is HTTPStatus.OK indicate success,

# otherwise indicate request is failed, you can get error code

# and message from code and message.

if resp.status_code == HTTPStatus.OK:

print(resp.output) # The output text

print(resp.usage) # The usage information

else:

print(resp.code) # The error code.

print(resp.message) # The error message.

sample_sync_call()

运行程序后发现几个错误:

首先,prompt=content,这里不对, prompt应该是“翻译成中文”

其次,程序在递归地处理同一个文件夹下的所有文件,包括已经生成的总结文件

让通义千问进行修改,最终修改后的Python代码如下:

import os

import time

from typing import List

from http import HTTPStatus

import dashscope

# API Key

API_KEY = "XXX"

# 遍历文件夹获取txt文件

def get_txt_files(directory: str) -> List[str]:

txt_files = []

for root, dirs, files in os.walk(directory):

txt_files.extend([

os.path.join(root, file)

for file in files

if file.endswith('.txt') and not file.endswith('_总结.txt')

])

return txt_files

# 读取txt文件内容,截断过长的内容

def read_and_truncate_file(file_path: str) -> str:

with open(file_path, 'r', encoding='utf-8') as f:

content = f.read()

if len(content) > 6000:

print(f"原始文件内容超过6000字符,已截断至前6000个字符:{file_path}")

content = content[:6000]

return content

# 使用API翻译并保存结果

def translate_and_save(file_path: str, content: str):

try:

# 在内容前添加“翻译成中文”的提示语

prompt_text = "翻译成中文:" + content

if len(prompt_text) > 6000:

print(f"原始文件内容与提示语组合后超过6000字符,已截断至前6000个字符:{file_path}")

prompt_text = prompt_text[:6000]

resp = dashscope.Generation.call(

model='qwen-turbo',

prompt=prompt_text,

api_key=API_KEY

)

if resp.status_code == HTTPStatus.OK:

output_text = str(resp.output)

summary_file_path = os.path.splitext(file_path)[0] + "_总结.txt"

with open(summary_file_path, 'w', encoding='utf-8') as f:

f.write(output_text)

print(f"成功获取翻译结果并保存至:{summary_file_path}")

print(f"使用信息:{resp.usage}")

else:

print(f"请求失败,错误代码:{resp.code},错误信息:{resp.message}")

except Exception as e:

print(f"处理文件 {file_path} 时遇到错误:{str(e)}")

def main():

directory = "D:\\AR"

txt_files = get_txt_files(directory)

for file_path in txt_files:

content = read_and_truncate_file(file_path)

print(f"正在处理文件:{file_path}...")

time.sleep(1) # 模拟控制请求频率,实际请根据API限流要求调整间隔时间

translate_and_save(file_path, content)

if __name__ == "__main__":

main()

修改后的程序,运行成功。