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()
相关推荐
0566467 小时前
agent学习Day15——SQLAlchemy 查询过滤、分页与历史列表接口
python·学习·fastapi
程序员爱德华8 小时前
Python与C++:异同点对比
c++·python
hangyuekejiGEO9 小时前
GEO技术服务选型指南
大数据·人工智能·python
软萌萌的19 小时前
Java Spring Boot 修改yml配置&加载顺序规则
java·spring boot·python
Dxy123931021610 小时前
Linux 编译安装 Python 3.12.10(多版本共存,不破坏系统Python)
linux·运维·python
持敬chijing11 小时前
Python概述
开发语言·python
赤羽尾风13 小时前
NumPy快速入门
python·numpy
倒流时光三十年13 小时前
第三阶段 26 · highlight 高亮(返回命中片段)
后端·python·django
久久学姐15 小时前
Python+Playwright+Pytest+BDD,用FSM打造高效测试框架
python·pytest·bdd·playwright·fsm