使用urllib 制作百度翻译功能的实例!
效果:
baidufanyi.gif
代码:
# 百度翻译
# Python 3.5.1
from urllib import request, parse
import json
url = 'http://fanyi.baidu.com/v2transapi'
context = input('请输入需要翻译的内容 :\> ')
if context >= '\u4e00' and context <= '\u9fa5':
# 判断输入内容是否为汉字
From,To = 'zh','en'
else:
From,To = 'en','zh'
data = {
'query':context,
'from':From,
'to':To,
'transtype':'translang',
'simple_means_flag':3
}
data = parse.urlencode(data).encode('utf-8')
r = request.Request(url,data)
r.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0')
html = request.urlopen(r).read().decode('utf-8')
Result = json.loads(html)
# 显示翻译结果
print(Result['trans_result']['data'][0]['dst'])
网友评论