本博客會給讀者一個非常好用的翻譯接口,主要是針對大量文本翻譯,可以突破翻譯限制(指的是一個IP可以連續翻譯,不是指一次翻譯很多文本),筆者親測翻譯數千條推特無壓力。
本翻譯腳本是使用的有道翻譯,需要你提前下載安裝python3的request
、json
和faker
庫。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)
博主親測github上googletrans
這個包對翻譯次數有限制,翻譯多了後就會拒絕服務;使用該腳本可以突破這個限制,目前csdn上大部分博客實現的翻譯次數都是有限制的,大家不妨試試這個腳本,非常的方便。