python3实现无限次翻译

\quad本博客会给读者一个非常好用的翻译接口,主要是针对大量文本翻译,可以突破翻译限制(指的是一个IP可以连续翻译,不是指一次翻译很多文本),笔者亲测翻译数千条推特无压力。
\quad本翻译脚本是使用的有道翻译,需要你提前下载安装python3的requestjsonfaker库。faker库主要用于产生随机的"user_agent"。最终程序如下:

from urllib import request, parse
import json
from faker import Faker

class trans(object):
    def __init__(self):
        self.url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'

    def tran(self, text):
        index = text.find("http")
        text = text[:index]
        text = text.replace('\n', '').replace('#', '').replace('RT ', '').replace(':', '')
        ua = Faker().user_agent()
        headers = {
            'User-Agent': ua,
            'Host': 'fanyi.youdao.com',
            'Origin': 'http://fanyi.youdao.com',
            'Referer': 'http://fanyi.youdao.com/',

        }
        # 表单数据
        from_data = {
            'i': text,
            'from': 'UTO',
            'to': 'UTO',
            'smartresult': 'dict',
            'client': 'fanyideskweb',
            'doctype': 'json',
            'version': '2.1',
            'keyfrom': 'fanyi.web',
            'action': 'FY_BY_REALTlME'
        }
        from_data = parse.urlencode(from_data).encode('utf-8')
        req = request.Request(self.url, from_data, headers)
        res = request.urlopen(req).read().decode("utf-8")
        target = json.loads(res)
        try:
            result = target['translateResult'][0][0]['tgt']
        except:
            result = "Translate failed"
        return result

if __name__ == '__main__':
    Obj = trans()
    text = "Egypt disinfecting streets in Cairo to combat the spread of Coronavirus.\n#COVID19Africa #CoronavirusPandemic\n https://t…"
    res = Obj.tran(text)
    print(res)

\quad博主亲测github上googletrans这个包对翻译次数有限制,翻译多了后就会拒绝服务;使用该脚本可以突破这个限制,目前csdn上大部分博客实现的翻译次数都是有限制的,大家不妨试试这个脚本,非常的方便。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章