需要实现的功能

程序命名:dreamdict

命令简写:ddt

需求:Unix/Linux系统命令行输入ddt word即可返回翻译结果,输入ddt不带文字则要求输入需要翻译的词语
centos_ddt

模块选择

Python包模块众多,其中urllib是Python3自带的,无需安装直接导入,而requests需要利用pip进行安装,在部署的时候需要在机器上安装,不然程序无法使用。

这里我分别写了两个程序,均可实现。

使用requests模块实现

#!/usr/bin/env python3

# 导入模块
import sys
import json
import time
import random
import hashlib
import requests

# 定义函数
def translate(content):
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    # 定义变量
    client = 'fanyideskweb'
    ctime = int(time.time() * 1000)
    # 定义加盐
    salt = str(ctime + random.randint(1, 10))
    key = 'aNPG!!u6sesA>hBAW1@(-'
    # 定义签名
    sign = hashlib.md5((client + content + salt + key).encode('utf-8')).hexdigest()
    # 定义data内容
    data = {}
    data['i'] = content
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = salt
    data['sign'] = sign
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_CL1CKBUTTON'
    data['typoResult'] = 'false'
    # 定义Header内容
    head = {}
    head['Accept'] = 'application/json, text/javascript, */*; q=0.01'
    head['Accept-Encoding'] = 'gzip, deflate'
    head['Accept-Language'] = 'zh-CN,zh;q=0.9'
    head['Connection'] = 'keep-alive'
    head['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    head['Cookie'] = 'OUTFOX_SEARCH_USER_ID=148563950@10.169.0.83; JSESSIONID=aaaDZZs7-QKurhSMz7eRw; OUTFOX_SEARCH_USER_ID_NCOO=1646923174.7677724; ___rl__test__cookies=' + str(ctime)
    head['Host'] = 'fanyi.youdao.com'
    head['Origin'] = 'http://fanyi.youdao.com'
    head['Referer'] = 'http://fanyi.youdao.com/'
    head['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'
    head['X-Requested-With'] = 'XMLHttpRequest'
    # 打包请求
    request = requests.request('POST', url, data = data, headers = head)
    # Json化返回数据
    a=json.loads(request.content)
    # 如果有smartResult则返回,如无则返回translateResult
    try:
        result = ''.join(a['smartResult']['entries'][1:])
    except KeyError:
        result = a['translateResult'][0][0]['tgt']
        return result
    else:
        return result
# 检测输入来源,如来自CLi则直接翻译,如无则要求用户输入
if len(sys.argv) > 1:
        content = ' '.join(sys.argv[1:])
else:
    content = input('请输入需要翻译的内容:')
# 调用函数
print(translate(content))

使用urllib包实现

  • 需要使用到urllib.requesturllib.parse两个模块
  • request到的数据因为是gzip压缩后的数据,需要经过zip模块处理,不然报错

目前只能在打包的数据不采用gzip,待后期测试修改。

#!/usr/bin/env python3

# 导入模块
import sys
import gzip
import json
import time
import random
import hashlib
import urllib.request
import urllib.parse

# 定义函数
def translate(content):
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    # 定义变量
    client = 'fanyideskweb'
    ctime = int(time.time() * 1000)
    # 定义加盐
    salt = str(ctime + random.randint(1, 10))
    key = 'aNPG!!u6sesA>hBAW1@(-'
    # 定义签名
    sign = hashlib.md5((client + content + salt + key).encode('utf-8')).hexdigest()
    # 定义data内容
    data = {}
    data['i'] = content
    data['from'] = 'AUTO'
    data['to'] = 'AUTO'
    data['smartresult'] = 'dict'
    data['client'] = 'fanyideskweb'
    data['salt'] = salt
    data['sign'] = sign
    data['doctype'] = 'json'
    data['version'] = '2.1'
    data['keyfrom'] = 'fanyi.web'
    data['action'] = 'FY_BY_CL1CKBUTTON'
    data['typoResult'] = 'false'
    # 定义Header内容
    head = {}
    head['Accept'] = 'application/json, text/javascript, */*; q=0.01'
    #head['Accept-Encoding'] = 'gzip, deflate'
    head['Accept-Language'] = 'zh-CN,zh;q=0.9'
    head['Connection'] = 'keep-alive'
    head['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    head['Cookie'] = 'OUTFOX_SEARCH_USER_ID=148563950@10.169.0.83; JSESSIONID=aaaDZZs7-QKurhSMz7eRw; OUTFOX_SEARCH_USER_ID_NCOO=1646923174.7677724; ___rl__test__cookies=' + str(ctime)
    head['Host'] = 'fanyi.youdao.com'
    head['Origin'] = 'http://fanyi.youdao.com'
    head['Referer'] = 'http://fanyi.youdao.com/'
    head['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.131 Safari/537.36'
    head['X-Requested-With'] = 'XMLHttpRequest'
    
    # 转化data数据
    data = urllib.parse.urlencode(data).encode()
    # 打包请求
    request = urllib.request.Request(url, data = data, headers = head)
    # 请求数据
    response = urllib.request.urlopen(request)
    # 转换返回数据格式
    html = response.read().decode('utf-8')

    # Json化返回数据
    a=json.loads(html)
    # 如果有smartResult则返回,如无则返回translateResult
    try:
        result = ''.join(a['smartResult']['entries'][1:])
    except KeyError:
        result = a['translateResult'][0][0]['tgt']
        return result
    else:
        return result
# 检测输入来源,如来自CLi则直接翻译,如无则要求用户输入
if len(sys.argv) > 1:
        content = ' '.join(sys.argv[1:])
else:
    content = input('请输入需要翻译的内容:')
# 调用函数
print(translate(content))

部署

以使用request模块开发的,部署到CentOS7的机器为例。

# 安装Python3,因为CentOS自带为2.7
yum install -y dnf
dnf install -y python36 python36-pip

# pip安装request模块
pip3 install request

# 拷贝代码
vi /usr/local/bin/ddt
将代码写入

# 添加执行权限
chmod +x /usr/local/bin/ddt

至此即可使用ddt word进行查询

已知问题

1.ddt后查询的词语中包含 ' 符号将无法开始查询
Last modification:May 17th, 2019 at 05:36 pm