批量文本翻译

多线程实现文本翻译:
但是这个包很坑,每天只能翻译很少的内容

"""
 -*- coding: utf-8 -*-
 author: Hao Hu
 @date   2022/5/23 5:35 PM
"""
#  多线程翻译
from translate import Translator
translator= Translator(to_lang="zh")
from tqdm import tqdm
import paramiko
from concurrent.futures import ThreadPoolExecutor
def analyse_txt():
    with open('./question.txt','r') as fp:
        contents = fp.readlines()
    en_list = []
    for sample in contents:
        tmp_sentence = sample[:-1]
        en_list.append(tmp_sentence)
    return en_list


def translate_english_to_chinese(tmp_sentence):
    """将英文翻译成中文"""
    en_zh_list = []
    translation = translator.translate(tmp_sentence)
    en_zh_list.append("{} *** {}".format(tmp_sentence,translation))
    
    return en_zh_list





if __name__ == '__main__':
    en_list = analyse_txt()
    executor = ThreadPoolExecutor(max_workers=20)
    en_zh_list = [executor.submit(translate_english_to_chinese, (tmp_sentence)) for tmp_sentence in en_list]
    end_list = []
    for sample in en_zh_list:
        end_list.append("{}\n".format(sample.result()[0]))
        
    with open('./en_zh_question.txt','w') as f:
         f.writelines(end_list)

免费版才是最香的!!!

接下来的代码只是部分,完整代码请访问

GitHub - Huhaobangbangbang/translate_english_to_chinese: We have two choice.One is multi-threaded, the other is free single-threaded provided by baidu

"""
 -*- coding: utf-8 -*-
 author: Hao Hu
 @date   2022/5/23 9:30 PM
"""
# totally free
from baidu_translate import TranslateClient
from time import sleep
from tqdm import tqdm
def analyse_txt():
    with open('./question.txt','r') as fp:
        contents = fp.readlines()
    en_list = []
    for sample in contents:
        tmp_sentence = sample[:-1]
        en_list.append(tmp_sentence)
    return en_list

def test():
    client = TranslateClient()
    print(client.auto2auto('你好, 这是个测试').text)
    print(client.zh2en('你好, 这是个测试').text)
    print(client.en2zh('Hello').text)


def translate_by_baidu(en_list):
    client = TranslateClient()
    en_zh_list = []
    for sample in tqdm(en_list):
        try:
            zh_sentence = client.en2zh(sample).text
            en_zh_list.append("{} *** {}\n".format(sample, zh_sentence))
            print(sample,zh_sentence)
            print('***')
            print(zh_sentence)
            sleep(1.2)
        except:
            pass
    return en_zh_list

if __name__ == '__main__':
    
    en_list = analyse_txt()
    #test()
    en_zh_list = translate_by_baidu(en_list)
    with open('./en_zh_question.txt', 'w') as f:
        f.writelines(en_zh_list)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值