python利用有道翻译实现"语言翻译器"的功能实例
2019/7/13 22:39:47
本文主要是介绍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利用有道翻译实现"语言翻译器"的功能实例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-08有遇到过吗?同样的规则 Excel 中 比Python 结果大
- 2024-03-30开始python成长之路
- 2024-03-29python optparse
- 2024-03-29python map 函数
- 2024-03-20invalid format specifier python
- 2024-03-18pool.map python
- 2024-03-18threads in python
- 2024-03-14python Ai 应用开发基础训练,字符串,字典,文件
- 2024-03-13id3 algorithm python
- 2024-03-13sum array elements python