Loading... **提供脚本代码实现离线输入中文翻译英文。** ## 模型下载地址 * [Helsinki-NLP/opus-mt-zh-en at main (huggingface.co)](https://huggingface.co/Helsinki-NLP/opus-mt-zh-en/tree/main) ## 配置虚拟环境 ``` # conda create -n fys python=3.11.5 # conda activate fys # pip install --upgrade pip # pip install transformers sentencepiece tensorflow torch # pip install tensorflow -i https://mirrors.aliyun.com/pypi/simple # pip install --force-reinstall sacremoses ``` ## 翻译脚本 ``` from transformers import AutoModelForSeq2SeqLM, AutoTokenizer # Load model model_name = "/Helsinki-NLP/opus-mt-zh-en" # Example model tokenizer = AutoTokenizer.from_pretrained(model_name, local_files_only=True) model = AutoModelForSeq2SeqLM.from_pretrained(model_name, local_files_only=True) def translate(text): inputs = tokenizer.encode(text, return_tensors="pt") outputs = model.generate(inputs) translated_text = tokenizer.decode(outputs[0], skip_special_tokens=True) return translated_text if __name__ == '__main__': try: while True: source_text = input("请输入要中文文本: ") if source_text.lower() == 'q': break translation = translate(source_text) print("翻译结果: ", translation) except Exception as e: print("发生错误:", e) input("按 Enter 键退出...") ``` ## 启动脚本 ``` python.exe -s cntoen.py pause ``` ## 目录介绍 ``` F:\python\fys F:\python\fys\Helsinki-NLP\opus-mt-zh-en F:\python\fys\fy.bat F:\python\fys\cntoen.py ``` 最后修改:2024 年 10 月 07 日 © 允许规范转载 赞 如果觉得我的文章对你有用,请随意赞赏