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设计】。

相关文章

django框架model orM使用字典作为参数,保存数据的方法分析

本文实例讲述了django框架model orM使用字典作为参数,保存数据的方法。分享给大家供大家参考,具体如下: 假设有一个字典,里面已经有了所有相关信息,现在想利用这个字典作为参数,...

Python 26进制计算实现方法

本文实例讲述了Python 26进制计算方法。分享给大家供大家参考。具体分析如下: 题目是这样的: 假设A=1,B=2,C=3...AA=27,AB=28...AAA=xxx(表示某个数...

python静态方法实例

本文实例讲述了python静态方法。分享给大家供大家参考。 具体实现方法如下: 复制代码 代码如下:staticmethod Found at: __builtin__ staticme...

Python求均值,方差,标准差的实例

如下所示: import numpy as np arr = [1,2,3,4,5,6] #求均值 arr_mean = np.mean(arr) #求方差 arr_var = n...

Python实现遍历windows所有窗口并输出窗口标题的方法

本文实例讲述了Python实现遍历windows所有窗口并输出窗口标题的方法。分享给大家供大家参考。具体如下: 这段代码可以让Python遍历当前Windows下所有运行程序的窗口,并获...