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()
相关推荐
deephub9 分钟前
Scikit-Learn 1.8引入 Array API,支持 PyTorch 与 CuPy 张量的原生 GPU 加速
人工智能·pytorch·python·机器学习·scikit-learn
free-elcmacom20 分钟前
机器学习高阶教程<11>当数据开始“折叠”:流形学习与深度神经网络如何发现世界的隐藏维度
人工智能·python·神经网络·学习·算法·机器学习·dnn
月明长歌1 小时前
Java数据结构:PriorityQueue堆与优先级队列:从概念到手写大根堆
java·数据结构·python·leetcode·
波克布林的矩阵6331 小时前
VS code为python文件配置默认模板
python
dhdjjsjs1 小时前
Day44 PythonStudy
python
love530love1 小时前
在 PyCharm 中配置 x64 Native Tools Command Prompt for VS 2022 作为默认终端
ide·人工智能·windows·python·pycharm·prompt·comfyui
柒.梧.1 小时前
CSS 基础样式与盒模型详解:从入门到实战进阶
人工智能·python·tensorflow
free-elcmacom1 小时前
机器学习高阶教程<9>从实验室到生产线:机器学习模型推理与部署优化实战指南
人工智能·python·机器学习
兴趣使然黄小黄1 小时前
【Pytest】Pytest常用的第三方插件
python·pytest
倔强的小石头_1 小时前
Python 从入门到实战(十一):数据可视化(用图表让数据 “说话”)
开发语言·python·信息可视化