Skip to content

Commit

Permalink
The first stable version.
Browse files Browse the repository at this point in the history
  • Loading branch information
cassvin committed Feb 26, 2012
0 parents commit 8e5d7a9
Show file tree
Hide file tree
Showing 3 changed files with 87 additions and 0 deletions.
10 changes: 10 additions & 0 deletions README
@@ -0,0 +1,10 @@
'hj' is a simple translator gadget which is based on HJ English.

To install hj, please run the setup.sh script.

You must have the root privilege. Otherwise you can use the 'sudo' command to simulate the root privilege.

Execute the script as follows:
./setup.sh
or
sudo ./setup.sh
73 changes: 73 additions & 0 deletions hj.py
@@ -0,0 +1,73 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Leon Hui
# email: cassvin91@gmail.com

import urllib
import sys
from pyquery.pyquery import PyQuery

#reload(sys)
#sys.setdefaultencoding('UTF-8')

URL = 'http://dict.hjenglish.com/app/w/'

class NoneError(Exception):
pass

def tr(itext):
if not itext:
raise NoneError
global URL
url = URL + urllib.quote(itext)
resp = urllib.urlopen(url)
html = resp.read()
resp.close()
return extract_otext(html)

def extract_otext(html):
pqhtml = PyQuery(html)
pron = pqhtml('.trsf')
mean = pqhtml('#panel_comment')
rs = {}

# 提取单词发音部分
if pron:
if pron.size() == 1:
s = '%s' % pron.eq(0).text()
else:
s = '%s: %s; ' % (pron.eq(0).attr('title'), pron.eq(0).text())
s += '%s: %s ' % (pron.eq(1).attr('title'), pron.eq(1).text())
rs['pron'] = s

# 提取单词意义部分
if mean:
s = mean.html().replace('<br />', '').replace('&#13', '')
rs['mean'] = s

return rs

if __name__ == '__main__':

print 'Welcome to Leon Hui\'s translator gadget!'

while True:
try:
itext = raw_input('>>> ').strip()
itext = itext.split()[0] if itext else None
rs = tr(itext)
except NoneError:
continue
except EOFError:
print '\r'
sys.exit(0)
except KeyboardInterrupt:
print '\r'
continue
except IOError, e:
print 'Error: %s' % e
continue
else:
print rs['pron'] if rs.get('pron') else None
print rs['mean'] if rs.get('mean') else None

4 changes: 4 additions & 0 deletions setup.sh
@@ -0,0 +1,4 @@
#!/bin/bash

cp hj.py /usr/local/bin
ln -s /usr/local/bin/hj.py /usr/local/bin/hj

0 comments on commit 8e5d7a9

Please sign in to comment.