有道翻译、小牛翻译Python[转载]



def YouDaoTranslator(eng="Who are you?"):
    #time.sleep(2)

    #输入句子
    keyword = eng

    #生成salt的值
    r = str(int(time.time()*1000))
    salt = r + str(int(random.random()*10))

    # 生成sign
    value = "fanyideskweb" + keyword + salt + "@6f#X3=cCuncYssPsuRUE"
    md5_str = getMd5(value)

    # 生成header
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Language': 'zh-CN,zh;q=0.9,und;q=0.8,en;q=0.7',
        'Connection': 'keep-alive',
        'Content-Length': str(233+len(keyword)),
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': 'OUTFOX_SEARCH_USER_ID=-1475131016@10.169.0.83; OUTFOX_SEARCH_USER_ID_NCOO=6241167.578427844; _ga=GA1.2.1519057173.1535511777; JSESSIONID=aaamFTGK4qLCf4uKcrxPw; ___rl__test__cookies=1556242390777',
        'Host': 'fanyi.youdao.com',
        'Origin': 'http://fanyi.youdao.com',
        'Referer': 'http://fanyi.youdao.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
    }

    # 生成表单数据
    data_dic = {
        'i': keyword,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': salt,
        'sign': md5_str,
        'ts': r,
        'bv': 'ae62d2e2541901f6ebf99ec18e429e3f',
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTlME'
    }

    # 接口地址
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule' #
    # 发起网络请求
    bool_ = False
    while bool_ is False:
        proxy = random.choice(proxies_list)
        print(proxy)
        try:
            response = requests.post(
                url=url,
                data=data_dic,
                headers=headers, 
                proxies=proxy, 
                timeout=3
                )
            sentences = []

            #print(response.text)
            json_ = response.json()
            for d in json_["translateResult"][0]:
                sentences.append(d['tgt'])
            paragraph = ''.join(sentences)

        except requests.exceptions.ReadTimeout:
            bool_ = False
            proxies_list.remove(proxy)
            print('[有道翻译]正在重新发送请求...[requests.exceptions.ReadTimeout]')
            #print(response.json())
        except requests.exceptions.ConnectionError:
            bool_ = False
            proxies_list.remove(proxy)
            print('[有道翻译]正在重新发送请求...[requests.exceptions.ConnectionError]')
            #print(response.json())
        except json.decoder.JSONDecodeError:
            bool_ = False
            print('[有道翻译]正在重新发送请求...[json.decoder.JSONDecodeError]')
            #print(response.json())
        else:
            bool_ = True
    #print(response.text)
    #print(json.dumps(response.json(),indent=4))
    #print(response.json())
    #print(response.json()["translateResult"][0])
    print([paragraph])
    return paragraph





def XiaoNiuTranslator_eng2chn(eng):
    """
    """
    QereyStringParameters = {

    "from": "en",
    "to": "zh",
    "m": "0.028638411098389938",
    "apikey": "e93b7ede2aa026df0f49e189a9b9ca89",
    "url": "",
    "t": "1558421027020"

    }

    QereyStringParameters.update({"src_text":eng})
    url = 'https://test.niutrans.vip/NiuTransServer/translation?' + urllib.parse.urlencode(QereyStringParameters)

    RequestHeaders = {

        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.87 UBrowser/7.0.185.1002 Safari/537.36"
    }

    FormData = {}

    bool_ = False
    while bool_ is False:
        proxy = random.choice(proxies_list)
        print(proxy)
        try:
            response = requests.get(
                url=url, 
                headers=RequestHeaders, 
                data=FormData, 
                proxies=proxy, 
                timeout=3
                )
        except:
            bool_ = False
            proxies_list.remove(proxy)
            print('[小牛翻译]正在重新发送请求...[requests.exceptions.ReadTimeout]')
        else:
            bool_ = True
    
    #s_code = response.status_code
    #print(s_code)
    json_data = response.json()
    print('\n', [json_data['tgt_text']])
    return json_data['tgt_text']



def eng2chn_by_YouDao_and_XiaoNiu(engtext='eng.txt', engchntext='eng-chn.txt'):
    '''
    engtext_to_engchntext(engtext='eng.txt', engchntext='eng-chn.txt')
    '''
    #XiaoNiu #api = 1
    #YouDao #api = 2
    #Bing #api = 3

    with open(engtext, 'r', encoding='utf8') as f:
        paragraphs_ = f.readlines()

    f = open(engchntext, 'w', encoding='utf8')
    for line_n in progressbar.progressbar(paragraphs_):
        if line_n == '\n':
            f.write(line_n)
        else:
            eng = line_n.rstrip('\n')
            print([eng])
            chn_YouDao = YouDaoTranslator(eng=eng)
            chn_XiaoNiu = XiaoNiuTranslator_eng2chn(eng=eng)
            print('==============\n\n')
            chn_YouDao = chn_YouDao.lstrip('\n').rstrip('\n')
            chn_XiaoNiu = chn_XiaoNiu.lstrip('\n').rstrip('\n')
            f.write(line_n)
            f.write(chn_YouDao+'\n'+chn_XiaoNiu+'\n\n')
        time.sleep(2)
    f.close()
# 注1:requests依赖IE代理设置,若IE代理设置有误(UC浏览器不能正常上网),则程序无法正确运行
# 注2:requests依赖IE代理设置,若本地代理被服务器禁封,则程序也无法正确运行


import requests
import time
import random
 
# 生成md5字符串
def getMd5(value):
    import hashlib
    md5 = hashlib.md5()
    md5.update(bytes(value, encoding='Utf-8'))
    md5_str = md5.hexdigest()
    return md5_str
 
if __name__ == '__main__':




    eng = '''"Don't be fooled by the political left  because we are the people of this nation that is witnessing  triumph," Voight continued. "So let us stand with our president , let us stand for  this truth that President Trump is the greatest president since Abraham Lincoln. God bless America." Voight is best known for his lead role as Joe Buck in the 1969 film "Midnight Cowboy." His decades-long career includes movie roles in "Deliverance," "Mission: Impossible," "Anaconda," "Zoolander," and "Transformers" as well as television roles in "24" and "Ray Donovan." The Academy Award-winning actor told his followers  that he wanted to "acknowledge the truth " that "our country is stronger, safer, and with more jobs" because President Trump "has made every move correct."'''


    #输入单词
    keyword = eng
 
    #生成salt的值
    r = str(int(time.time()*1000))
    salt = r + str(int(random.random()*10))
 
    #生成sign
    value = "fanyideskweb" + keyword + salt + "@6f#X3=cCuncYssPsuRUE"
    md5_str = getMd5(value)
 
    #生成header
    headers = {
        'Accept': 'application/json, text/javascript, */*; q=0.01',
        'Accept-Language': 'zh-CN,zh;q=0.9,und;q=0.8,en;q=0.7',
        'Connection': 'keep-alive',
        'Content-Length': str(233+len(keyword)),
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
        'Cookie': 'OUTFOX_SEARCH_USER_ID=-1475131016@10.169.0.83; OUTFOX_SEARCH_USER_ID_NCOO=6241167.578427844; _ga=GA1.2.1519057173.1535511777; JSESSIONID=aaamFTGK4qLCf4uKcrxPw; ___rl__test__cookies=1556242390777',
        'Host': 'fanyi.youdao.com',
        'Origin': 'http://fanyi.youdao.com',
        'Referer': 'http://fanyi.youdao.com/',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36',
        'X-Requested-With': 'XMLHttpRequest'
    }
 
    #生成表单数据
    data_dic = {
        'i': keyword,
        'from': 'AUTO',
        'to': 'AUTO',
        'smartresult': 'dict',
        'client': 'fanyideskweb',
        'salt': salt,
        'sign': md5_str,
        'ts': r,
        'bv': 'ae62d2e2541901f6ebf99ec18e429e3f',
        'doctype': 'json',
        'version': '2.1',
        'keyfrom': 'fanyi.web',
        'action': 'FY_BY_REALTlME'
    }
 
    #接口地址
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    #发起网络请求
    response = requests.post(url=url,data=data_dic,headers=headers)
    #print(response.text)
    print(response.json())




原文地址:http://www.icode9.com/content-1-174533.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值