脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python 20行简单实现有道在线翻译的详解

Python 20行简单实现有道在线翻译的详解

2021-06-27 00:03kongfu_cat Python

这篇文章主要介绍了Python实现有道在线翻译的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

简介

主要是尝试简单的使用pyhton的爬虫功能,于是使用有道进行尝试,并没有进行深入的诸如相关api的调用。

以下是需要的post数据

Python 20行简单实现有道在线翻译的详解

代码

以下是相关部分的代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import urllib.request
import urllib.parse
import json
 
content=input('需要翻译的内容:')
#翻译内容
 
url='http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&sessionfrom=http://fanyi.youdao.com/'
#有道翻译查询入口
data = #表单数据
   'i': content,
   'from': 'auto',
   'to': 'auto',
   'smartresult': 'dict',
   'client': 'fanyideskweb',
   'doctype': 'json',
   'version': '2.1',
   'keyfrom': 'fanyi.web',
   'action': 'fy_by_clickbuttion',
   'typoresult': 'false'
  }
 
data=urllib.parse.urlencode(data).encode('utf-8')
#对post数据进行编码
 
response=urllib.request.urlopen(url,data)
#发出post请求并获取http响应
 
html=response.read().decode('utf-8')
#获取网页内容,并进行解码解码
 
target=json.loads(html)
#json解析
 
print("\n翻译结果:%s"%target['translateresult'][0][0]['tgt'])
#输出翻译结果

重要函数

urllib.request.urlopen()——发送post数据,同时返回响应

urllib.parse.urlencode()——对post数据进行编码转换

json.loads()——进行json解析

以上所述是小编给大家介绍的python实现有道在线翻译的方法详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!

原文链接:https://blog.csdn.net/kongfu_cat/article/details/79682030
 

延伸 · 阅读

精彩推荐