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()
相关推荐
qq74223498411 分钟前
Python操作数据库之pyodbc
开发语言·数据库·python
2401_841495641 小时前
【自然语言处理】轻量版生成式语言模型GPT
人工智能·python·gpt·深度学习·语言模型·自然语言处理·transformer
云和数据.ChenGuang1 小时前
tensorflow生成随机数和张量
人工智能·python·tensorflow
测试老哥2 小时前
python+requests+excel 接口测试
自动化测试·软件测试·python·测试工具·测试用例·excel·接口测试
AI纪元故事会2 小时前
冰泪与雨丝:一个AI的Python挽歌
开发语言·人工智能·python
ColderYY2 小时前
Python连接MySQL数据库
数据库·python·mysql
寒秋丶3 小时前
Milvus:数据库层操作详解(二)
数据库·人工智能·python·ai·ai编程·milvus·向量数据库
凯歌的博客3 小时前
python虚拟环境应用
linux·开发语言·python
西柚小萌新3 小时前
【深入浅出PyTorch】--8.1.PyTorch生态--torchvision
人工智能·pytorch·python
MonkeyKing_sunyuhua3 小时前
can‘t read /etc/apt/sources.list: No such file or directory
python