实现了在线翻译功能。
@@ 实例: http://www.mykurol.com
效果:
views.py
def youdaofanyi(request):
'''
有道翻译功能
'''
import json
from urllib import parse
import urllib.request, urllib.parse, urllib.request
query = {} # 定义需要翻译的文本
fanyi = request.POST.get('fanyi_content', '')
query['q'] = fanyi # 输入要翻译的文本
url = 'http://fanyi.youdao.com/openapi.do?keyfrom=11pegasus11&key=273646050&type=data&doctype=json&version=1.1&' + parse.urlencode(
query) # 有道翻译api
response = urllib.request.urlopen(url, timeout=3)
# response = urllib.parse.urlopen(url)
# 编码转换
try:
html = response.read().decode('utf-8')
d = json.loads(html)
explains = d.get('basic').get('explains') # 翻译后输出
a1 = d.get('basic').get('uk-phonetic') # 英式发音
a2 = d.get('basic').get('us-phonetic') # 美式发音
explains_list = []
for result in explains:
explains_list.append(result)
# 输出
fanyi_dict = {
'q': query['q'],
'yinshi': a1,
'meishi': a2,
'explains_list': explains_list,
}
return fanyi_dict
except Exception as e:
print (e)
def listblogs(request):
fanyi_dict = {}
fanyi_form = fanyiForm()
if request.method == 'POST':
fanyi_form = fanyiForm(request.POST)
if fanyi_form.is_valid():
fanyi_dict = youdaofanyi(request)
# #
bloglist = {
'fanyi_form' : fanyi_form, # 翻译的表单
'fanyi_dict' : fanyi_dict, # 翻译出来的文本
}
return render(request, 'fanyi.html', bloglist)
forms.py
class fanyiForm(forms.Form):
'''
翻译功能表单
'''
fanyi_content = forms.CharField(label='翻译', error_messages={
'required': '请填写需要翻译的内容',
'max_length': '填写的内容太长'
}, widget=forms.Textarea(attrs={'class': 'form-control', 'id': 'exampleInputContent', 'placeholder': '请输入要翻译的文字', 'rows': '1'}))
fanyi.html
<form action="#" method="post">
{% csrf_token %}
<div style="width: 318px">
<div class="form-group" style="width: 230px; padding: 30px 5px 30px 30px; float: left">
{{ fanyi_form.fanyi_content }}
</div>
<button type="submit" class="btn btn-default" style="float: left;margin:30px 30px 30px 0;">翻译</button>
{% if fanyi_dict %}
<div class="fanyitext" style="width: 249px;float: left; padding: 10px; margin-left: 30px; border: 1px solid rgba(0,0,0,0.08);">
<p align="center">有道词典结果</p>
<p><b>【{{ fanyi_dict.q }}】</b></p>
<p><span>英:</span>
<span style="color: #a0a0a0;">[{{ fanyi_dict.yinshi }}]</span>
<span style="margin-left: 20px">美:</span>
<span style="color: #a0a0a0;">[{{ fanyi_dict.meishi }}]</span>
</p>
{% for explains in fanyi_dict.explains_list %}
<p>{{ explains }}</p>
{% endfor %}
</div>
{% endif %}
</div>
</form>