python控制台英汉汉英电子词典
用python实现了下控制台电子词典,数据来自有道,通过向有道发送http表单数据,然后将服务器返回的json数据解析得到翻译结果,代码比较简单,练练手!
# coding=utf-8 # Filename: trans.py # Author: qianghaohao(CodeNutter) # Email: codenutter@foxmail.com # Program: 控制台电子词典 # import os import sys import requests import random import json # import chardet # 第三方模块检查字符串编码,用于调试 from requests.exceptions import ConnectionError, Timeout # os.system('set PYTHONIOENCODING=UTF-8') def GetHelp(): U''' GNU trans 1.0 By qianghaohao(CodeNutter) Usage: trans [OPTION] [statements] --version 版本信息 --help 使用帮助 Example: trans campus trans --version trans --help ''' pass if (len(sys.argv) < 2): print ''' trans: missing OPTION Usage: trans [OPTION] [statements] Try 'trans --help' for more details! ''' sys.exit(1) if sys.argv[1].startswith('--'): option = sys.argv[1][2:] if option == 'version': print 'trans: Version 1.0' elif option == 'help': print GetHelp.__doc__ else: print ''' Unknown option! Try 'trans --help' for more options! ''' sys.exit(2) else: to_be_trans = ' '.join(sys.argv[1:]).decode('GB2312').encode('utf-8') # print chardet.detect(to_be_trans) # 第三方模块检查字符串编码,用于调试 # --------有道翻译表单数据-------- data={} data['type']='AUTO' data['i']=to_be_trans data['doctype']='json' data['xmlVersion']='1.8' data['keyfrom']='fanyi.web' data['ue']='UTF-8' data['action']='FY_BY_CLICKBUTTON' data['typoResult']='true' youdao_url = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule&smartresult=ugc&sessionFrom=dict2.index' # ---------- http报头:用户代理 ---------------- USER_AGENTS = ( 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:11.0) Gecko/20100101 Firefox/11.0', 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:22.0) Gecko/20100 101 Firefox/22.0', 'Mozilla/5.0 (Windows NT 6.1; rv:11.0) Gecko/20100101 Firefox/11.0', ('Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_4) AppleWebKit/536.5 (KHTML, like Gecko) ' 'Chrome/19.0.1084.46 Safari/536.5'), ('Mozilla/5.0 (Windows; Windows NT 6.1) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.46' 'Safari/536.5') ) # --------- 模拟手工请求:随机切换用户代理 --------- headers = {'User-Agent':random.choice(USER_AGENTS)} try: r = requests.post(youdao_url, timeout=10, headers=headers, data=data) except ConnectionError: print 'Network connection failed!' sys.exit(1) except Timeout: print 'request timeout!' sys.exit(1) result = r.json() print result['translateResult'][0][0]['tgt'].encode(sys.stdout.encoding)
使用示例(如果感兴趣的朋友可以用pyinstaller工具将py源码转换成exe格式,直接执行,比较方便,在此用解释器执行):
附源码地址:电子词典
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。
赞 (0)