当前位置: 移动技术网 > IT编程>脚本编程>Python > python利用有道翻译实现

python利用有道翻译实现

2017年12月08日  | 移动技术网IT编程  | 我要评论
实例如下: import urllib.request import urllib.parse import json while True: c

实例如下:

import urllib.request
import urllib.parse
import json

while True:
  content = input('请输入需要翻译的内容(退出输入Q):')
  if content == 'Q':
    break
  else:
    url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=http://www.youdao.com/'
    data = {}

    data['type'] = 'AUTO'
    data['i'] = content
    data['doctype'] = 'json'
    data['xmlVersion'] = '1.8'
    data['keyfrom'] = 'fanyi.web'
    data['ue'] = 'UTF-8'
    data['action'] = 'FY_BY_CLICKBUTTON'
    data['typoResult'] = 'true'

    data = urllib.parse.urlencode(data).encode('utf-8')
    response = urllib.request.urlopen(url, data)
    html = response.read().decode('utf-8')
    target = json.loads(html)
    print('翻译的结果:%s' % target['translateResult'][0][0]['tgt'])

程序执行情况:

这里要注意的是两个函数urllib.request.urlopen()与urllib.parse.urlencode()。

urllib.request.urlopen()其实不止一个参数,有好几个哦,其中第二个是data,data应该是一个buffer的标准应用程序/ x-www-form-urlencoded格式(python标准库原文:data should be a buffer in the standard application/x-www-form-urlencoded format)。urllib.parse.urlencode()函数接受一个映射或序列集合,并返回一个字符串的格式(python标准库原文:The urllib.parse.urlencode() function takes a mapping or sequence of 2-tuples and returns a string in this format)。我们可以看看urllib.parse.urlencode()的结果是什么样的:

上图的结果刚好与urllib.request.urlopen()的data参数的数据类型要求一致了。

注意,上面urlopen当中的url,这个是分析有道翻译页面的真实的Request URL:

以上这篇python利用有道翻译实现"语言翻译器"的功能实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如您对本文有疑问或者有任何想说的,请点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网