命令行有道翻译,可添加到单词本

有时碰到一个单词,顺手用命令行查询下比较方便,另外比较喜欢有道翻译中有道单词本的复习计划,加入单词本后可以在手机上看。

使用示例:

➜  ~  yd kiss
kiss [kis]
vt.吻;(风等)轻拂
vi.接吻;(风等)轻触
n.吻;轻拂

more: http://dict.youdao.com/search?keyfrom=webwordbook&q=kiss
➜  ~~  yd 无奈  
无奈 [wú nài]
1. however
2. cannothelpbut

more: http://dict.youdao.com/search?keyfrom=webwordbook&q=%E6%97%A0%E5%A5%88
➜  ~~  yd python -j
python ['paiθən, -θɔn]
n.巨蟒;大蟒;丹舌

more: http://dict.youdao.com/search?keyfrom=webwordbook&q=python
word list: http://dict.youdao.com/wordbook/wordlist?keyfrom=dict.result
➜  ~  

源代码如下:

linux / python 2.7 /2013:04:27 update

  1 #!/usr/bin/env python
  2 #encoding=utf-8
  3 
  4 import os
  5 import sys
  6 import codecs
  7 import re
  8 import urllib
  9 
 10 import httplib2
 11 #httplib2.debuglevel = 1
 12 
 13 h = httplib2.Http()
 14 user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.4 (KHTML, like Gecko) Chrome/22.0.1229.94 Safari/537.4"
 15 
 16 
 17 def youdao_traslate(word_input):
 18     '''
 19     mobile:
 20        English:http://dict.youdao.com/m/search?keyfrom=dict.mindex&vendor=&q=mouse
 21        Chinese:http://dict.youdao.com/m/search?keyfrom=dict.mindex&vendor=&q=%E7%BF%BB%E8%AF%91
 22    '''
 23     def is_not_found(html):
 24         not_found = '没有找到'
 25         if html.find(not_found) != -1:
 26             return True
 27         return False
 28 
 29     word = urllib.quote(word_input)
 30     url = 'http://dict.youdao.com/m/search?keyfrom=dict.mindex&vendor=&q=' + word
 31     #print url
 32     #pc:http://dict.youdao.com/search?keyfrom=webwordbook&q=mouse
 33     pc_url = 'http://dict.youdao.com/search?keyfrom=webwordbook&q=' + word
 34 
 35     resp, content = h.request(url)
 36     pat_content = re.compile(
 37         r'''
 38         <div><span><b>.*?</b></span>(.*?)
 39         <div\ class="content">(.*?)</div>
 40         ''', re.S | re.X
 41     )
 42     result = pat_content.findall(content)
 43     if not result:
 44         if is_not_found(content):
 45             msg = '''抱歉,没有找到与您查询的"%s"相符的字词.\ntry: %s''' % (word_input, pc_url)
 46         else:
 47             msg = '''Can not find result, check the regex!\nsee: %s ''' % url
 48         raise Exception(msg)
 49     else:
 50         result = result[0]
 51 
 52     # 1 find soundmark    一些单词,如娱乐,没有音标
 53     soundmark = result[0]
 54     pat_soundmark = re.compile(r'<span>(.*?)</span>', re.S)
 55     soundmark = pat_soundmark.findall(soundmark)
 56     if not soundmark:
 57         soundmark = ''
 58     else:
 59         soundmark = soundmark[0]
 60 
 61     # 2 find translate
 62     content = result[1]
 63     content = content.replace('\n', '').replace('<br/>', '\n').replace(' ', '').replace('\t', '')
 64     #for 中文查询
 65     content = content.replace('&nbsp;', ' ')
 66     content = content.strip()
 67 
 68     print word_input, soundmark
 69     print content
 70     print
 71     print 'More:', pc_url
 72 
 73 
 74 def youdao_login(username, password):
 75     #注意是https, http不行
 76     url = "https://reg.163.com/logins.jsp"
 77     body = {
 78         "url": "http://account.youdao.com/login?service=dict&back_url=http%3A%2F%2Fdict.youdao.com&success=1",
 79         "product": "search",
 80         "type": "1",
 81         "username": username,
 82         "password": password,
 83         "savelogin": "1"
 84     }
 85     #content-type 不能少
 86     headers_form = {
 87         "User-Agent": user_agent,
 88         "Content-Type": "application/x-www-form-urlencoded"
 89     }
 90 
 91     resp, content = h.request(url, method='POST', body=urllib.urlencode(body), headers=headers_form)
 92     #print resp
 93     cookie = resp['set-cookie']
 94     if not cookie:
 95         raise
 96     return cookie
 97 
 98 
 99 def youdao_wordlist(word, cookie):
100     #添加单词,会自动添加单词信息
101     add_word_url = 'http://dict.youdao.com/wordbook/ajax?action=addword&q=' + word
102 
103     headers = {
104         "User-Agent": user_agent,
105         "Cookie": cookie
106     }
107 
108     resp, content = h.request(add_word_url, headers=headers)
109 
110     if content != '{"message":"adddone"}':
111         raise Exception(content)
112 
113 
114 def write_to_file(file_name, txt):
115     with codecs.open(file_name, "w", "utf-8") as f:
116         f.write(txt)
117 
118 
119 def read_from_file(file_name):
120     with codecs.open(file_name, "r", "utf-8") as f:
121         txt = f.read()
122         txt = txt.encode('utf-8')
123     return txt
124 
125 
126 if __name__ == '__main__':
127     if len(sys.argv) == 1:
128         print 'Usage: yd word [-j]'
129         sys.exit()
130 
131     word = sys.argv[1]
132     # 1) 翻译单词
133     try:
134         youdao_traslate(word)
135     except Exception as e:
136         print e
137         exit()
138 
139     # 2) 是否加入单词本
140     msg = 'Add to wordlist? y/n '
141     if raw_input(msg) == 'y':
142         for i in range(3):
143             cookie_txt = 'youdao_cookie.txt'
144             if os.path.isfile(cookie_txt):
145                 cookie = read_from_file(cookie_txt)
146             else:
147                 username = 'username'
148                 password = 'password'
149 
150                 cookie = youdao_login(username, password)
151                 write_to_file(cookie_txt, cookie)
152 
153             try:
154                 youdao_wordlist(word, cookie)
155             except Exception as e:
156                 #删除过期的cookie,之后检查文件不存在会写入新的cookie
157                 os.system("rm youdao_cookie.txt -f")
158                 if str(e) != '{"message":"nouser"}':
159                     print 'Fail: %s' % e
160                     break
161             else:
162                 print 'Success: http://dict.youdao.com/wordbook/wordlist?keyfrom=dict.result'
163                 break
164         else:
165             print 'Error.'

 

将上面代码保存为 yd,加上可执行权限,即可像示例那样使用。如要使用加入单词本,把username,password 改成自己的即可。

将该程序添加为自定义命令详见 linux 添加管理自定义命令

posted @ 2012-11-05 11:52  congbo  阅读(3595)  评论(6编辑  收藏  举报