txt中文翻译成英文

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()

你可能感兴趣的:(python)