目前脚本只是简单处理txt文本翻译,如果需要其他的翻译,可以通过修改read和write函数来实现。
翻译后的lua文档附附件了,使用的是qwen3-4b-q8模型,楼主电脑实机跑了近半个小时。
重点关注
1、脚本默认关闭了思考,如果需要开启,将"think": False更改为"think": True
2、脚本重要参数:
limit
,此参数控制着后续翻译过程中提交给模型的字符数,过大会导致ollama空转,耗你电费而出不来结果。默认设置为5500,如果使用的话,可以选择自己进行调试。
3、脚本的另外一个重要参数就是:prompt,描述越准确,模型给出的结果会更趋向你想要的,但是楼主也是新手,代码中的只供参考。
代码
[Python] 纯文本查看 复制代码import os
import requests
import time
# Ollama 服务器的地址(默认本地)
OLLAMA_HOST = "http://localhost:11434"
# 获取已安装的模型列表
def get_installed_models():
"""获取已安装的模型列表"""
try:
response = requests.get(f"{OLLAMA_HOST}/api/tags")
response.raise_for_status() # 检查HTTP错误
models = response.json().get("models", [])
return [model["name"] for model in models]
except requests.exceptions.RequestException as e:
print(f"获取模型失败: {e}")
return []
# 模型选择函数
def select_model(models):
"""让用户选择模型"""
if not models:
print("没有找到可用模型!")
return None
print("\n可用的模型:")
for i, model in enumerate(models, 1):
print(f"{i}. {model}")
while True:
try:
choice = int(input("\n请选择模型 (输入编号): "))
if 1 list:
content_list = []
t = []
if contents:
for c in contents:
t.append(c)
if is_exceeding_limit(''.join(t)):
# 如果当前内容超过限制,将其添加到列表中
t.pop()
content_list.append(''.join(t))
t.clear()
t.append(c)
# 测试使用打印列表
# print(len(content_list))
# print(content_list)
return content_list
# 判断内容是否超过限制,默认限制为5500个字符
def is_exceeding_limit(text: str, limit: int = 5500) -> bool:
return len(text) >limit
# 主程序
if __name__ == "__main__":
# 获取并选择模型
models = get_installed_models()
selected_model = select_model(models)
if selected_model:
# print(f"\n已选择模型: {selected_model}")
file_path = input("请输入文件路径: ")
context = read_file(file_path)
if not context:
print("没有内容")
exit()
# 分割文本内容
content_list = manage_content(context)
# 判断获取到内容的大小
c_size = len(content_list)
response_list = []
for num , content in enumerate(content_list):
start_time = time.time()
print(f"正在处理第{num+1}段内容,总计{c_size}段内容")
#
prompt = "你是一名专业的编程工程师,精通lua语言,目前正在翻译一个帮助文档,帮助自己的学生学习lua语言,保持内容原有格式,不添加额外内容,请开始对内容进行翻译,翻译采用的语言为简体中文。"
prompt +="\n"+"".join(content)
# qwen 系列去思考过程 "/no_think"
# prompt += "\n" + "".join(content)++"/no_think"
# 测试打印输入文本
# print( prompt)
# break
# 向ollama 提交请求
response = generate_response(selected_model, prompt)
if response:
end_time = time.time()
# 单个段落翻译时间
print(f"翻译完成,耗时{end_time - start_time:.2f}秒")
# 测试,打印输出响应
# print(response)
# break
response_list.append(response)
write_file(file_path,response_list)