txt英文翻译成中文


import os
import argparse
from translate import Translator

def remove_old_translated():
    mypath = os.path.dirname(os.path.abspath(__file__))
    for f in os.listdir(mypath):
        if f.startswith("translated"):
            os.remove(f)

def remove_old_temps():
    mypath = os.path.dirname(os.path.abspath(__file__))
    for f in os.listdir(mypath):
        if f.startswith("temp"):
            os.remove(f)

class Translation:
    def __init__(self, from_language, to_language, extract_file, translate_file, transformed_file):
        self.from_language = from_language
        self.to_language = to_language
        self.extract_file = extract_file
        self.translate_file = translate_file
        self.transformed_file = transformed_file
        with open(self.extract_file, 'a') as f:
            f.write('\n')

    def clean_text(self):
        with open(self.extract_file, 'r') as f1:
            text = f1.read()
        text = text.replace('\n', '\n ')
        text = text.replace('\n', '')
        text = text.replace('.', '.\n')
        text = text.replace('!', '!\n')
        text = text.replace('?', '?\n')
        with open(self.transformed_file, 'w') as f2:
            f2.write(text)

    def translate_text(self, text):
        translator = Translator(to_lang=self.to_language, from_lang=self.from_language)
        translation = translator.translate(text)
        return translation

    def write_translation(self):
        with open(self.transformed_file, 'r') as f1, open(self.translate_file, 'w') as f2:
            for i, line in enumerate(f1, 1):
                f2.write(str(i) + ') ' + str(line.strip()) + '\n')
                f2.write(str(i) + ') ' + str(self.translate_text(line.strip())) + '\n\n')

if __name__ == "__main__":
    remove_old_translated()
    mypath = os.path.dirname(os.path.abspath(__file__))
    for f in os.listdir(mypath):
        if f.endswith(".txt"):
            argparser = argparse.ArgumentParser()
            argparser.add_argument('from_language', help="Example of command to run: python TranslateText.py fr en")
            argparser.add_argument('to_language', help="Example of command to run: python TranslateText.py fr en")
            args = argparser.parse_args()
            extract_file = "{}.txt".format(os.path.splitext(f)[0])
            transformed_file = "temp_{}.txt".format(os.path.splitext(f)[0])
            translate_file = "translated_{}_{}_{}.txt".format(args.from_language, args.to_language, os.path.splitext(f)[0])
            t = Translation(args.from_language, args.to_language, extract_file, translate_file, transformed_file)
            t.clean_text()
            t.write_translation()
            remove_old_temps()
            print('Translation complete - check the text file that starts with "translated"')


你可能感兴趣的:(python,开发语言)