txt中文翻译成英文

python 复制代码
from deep_translator import GoogleTranslator
import re
import sys

# Set the encoding for stdout to 'utf-8'
sys.stdout = open(sys.stdout.fileno(), mode='w', encoding='utf-8', buffering=1)

# Open input and output files
with open('input.txt', 'r', encoding='gbk') as fin, open('english.txt', 'a+', encoding='utf-8') as fout:
    # Get the number of already translated lines
    translated_lines = len(fout.readlines())
    fout.seek(0, 2)  # Move the file pointer to the end of the file for appending

    # Read and translate text line by line
    for i, line in enumerate(fin, start=1):
        # If this line has already been translated, skip it
        if i <= translated_lines:
            continue

        # Use regular expression to remove special characters
        line = re.sub(r'[^\w\s]', '', line)
        # Translate the text
        translation = GoogleTranslator(source='zh-CN', target='en').translate(line)
        # Print the line number and translation
        print(f"Line {i}: {translation}")
        # Write the translation to the output file and immediately save it
        fout.write(translation + '\n')
        fout.flush()
相关推荐
ID_180079054733 小时前
Python结合淘宝关键词API进行商品价格监控与预警
服务器·数据库·python
玄同7653 小时前
Python 自动发送邮件实战:用 QQ/163 邮箱发送大模型生成的内容
开发语言·人工智能·python·深度学习·机器学习·邮件·邮箱
岱宗夫up3 小时前
神经网络(MLP)在时间序列预测中的实践应用
python
我的xiaodoujiao3 小时前
使用 Python 语言 从 0 到 1 搭建完整 Web UI自动化测试学习系列 46--撰写 README项目说明文档文件
python·学习·测试工具·pytest
Olamyh3 小时前
【手搓 ReAct Agent:告别框架,回归本质】
人工智能·python
数研小生3 小时前
Python自然语言处理:NLTK与Gensim库
开发语言·python·自然语言处理
love530love3 小时前
Windows 下 GCC 编译器安装与排错实录
人工智能·windows·python·gcc·msys2·gtk·msys2 mingw 64
程序员ken3 小时前
深入理解大语言模型(8) 使用 LangChain 开发应用程序之上下文记忆
人工智能·python·语言模型·langchain
wazmlp0018873694 小时前
第五次python作业
服务器·开发语言·python
尘缘浮梦4 小时前
websockets简单例子1
开发语言·python