效果:
代码:
# 百度翻译 # 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‘])
时间: 2024-11-03 20:52:09