python利用有道翻译实现"语言翻译器"的功能实例

yipeiwu_com6年前Python基础

实例如下:

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利用有道翻译实现"语言翻译器"的功能实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

使用python实现mqtt的发布和订阅

需要安装的python库 使用python编写程序进行测试MQTT的发布和订阅功能。首先要安装:pip install paho-mqtt 测试发布(pub) 我的MQTT部署在阿里云的...

python中map、any、all函数用法分析

本文实例讲述了python中map、any、all函数用法。分享给大家供大家参考。具体分析如下: 最近想学python,就一直比较关注python,昨天在python吧看到有个帖子提问怎...

python3中dict(字典)的使用方法示例

一、clear(清空字典内容) stu = { 'num1':'Tom', 'num2':'Lucy', 'num3':'Sam', } print(stu.clear...

Python程序设计入门(5)类的使用简介

一、类的定义和使用 python定义一个类的基本语法是: 复制代码 代码如下:class classname([基类一,基类二...]):     [def...

Python zip()函数用法实例分析

本文实例讲述了Python zip()函数用法。分享给大家供大家参考,具体如下: 这里介绍python中zip()函数的使用: >>> help(zip) Help...