Skip to content

Instantly share code, notes, and snippets.

@xiongjia
Created March 1, 2015 14:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xiongjia/d74c3d97404ce2be8e77 to your computer and use it in GitHub Desktop.
Save xiongjia/d74c3d97404ce2be8e77 to your computer and use it in GitHub Desktop.
Online Dictionary API Tests
#!/usr/bin/env python
import os, sys, logging, getopt, ConfigParser, urllib2
class Log(object):
_LEVELS = {
"error": logging.ERROR,
"debug": logging.DEBUG,
"info": logging.INFO
}
def __init__(self, opts):
self._logger = logging.getLogger()
self.set_opts(opts)
def set_opts(self, opts):
if opts.get("console", False):
# enable console logger
out_hdlr = logging.StreamHandler(sys.stdout)
self._logger.addHandler(out_hdlr)
# update log level
self._logger.setLevel(self._get_log_level(opts.get("Level", "info")))
def get_logger(self):
return self._logger
def _get_log_level(self, log_level):
return self._LEVELS.get(log_level, logging.INFO)
# init logger
LOGGER = Log({ "Level": "debug", "console": True })
LOG = LOGGER.get_logger()
def load_config(conf_filename):
filename = conf_filename
if os.path.isabs(filename) == False:
filename = os.path.join(os.path.expanduser("."), filename)
filename = os.path.normpath(filename)
LOG.debug("Load config from %s", filename)
try:
cfg = ConfigParser.RawConfigParser()
cfg.read(filename)
return {
"youdao": {
"key" : cfg.get("youdao", "key"),
"keyfrom" : cfg.get("youdao", "keyfrom")
}
}
except Exception, err:
LOG.warn("Cannot load config from %s; err %s", full_filename, err)
raise
def print_usage():
print("""Dictionary.py
--query <query string>
""")
class Dictionary(object):
def query(self, query_str):
raise NotImplementedError("NotImplemented")
class YoudaoDictionary(Dictionary):
def __init__(self, cfg):
self._apiPrefix = "http://fanyi.youdao.com/openapi.do"
self._apiPrefix += "?keyfrom=%s&key=%s" % (cfg["keyfrom"], cfg["key"])
self._apiPrefix += "&type=data&doctype=jsonp&callback=show&version=1.1"
def query(self, query_str):
reqUrl = "%s&q=%s" % (self._apiPrefix, query_str)
req = urllib2.Request(reqUrl)
try:
rep = urllib2.urlopen(req)
data = rep.read()
except urllib2.HTTPError, http_err:
LOG.error("Cannot access server. HTTP code %s", http_err.code)
raise http_err
except Exception, err:
LOG.error("HTTP Request error %s", err)
raise err
return ("Youdao: %s" % str(data).decode("utf-8", errors = "replace"))
class DictManager(object):
def __init__(self, cfg):
self._dict = {
"youdao": YoudaoDictionary(cfg["youdao"])
}
self._defaultDict = "youdao"
def get_dict(self, name):
return self._dict[name]
def get_default_dict(self):
return self.get_dict(self._defaultDict)
def query(self, query_str):
curDict = self.get_default_dict()
return curDict.query(query_str)
def main():
LOG.info("start dictionary test")
# load config
LOG.debug("load config dictionary.cfg")
cfg = load_config("dictionary.cfg")
dictMgr = DictManager(cfg)
# Parse options
try:
opts, args = getopt.getopt(sys.argv[1:], "hq:", ["help", "query="])
except getopt.GetoptError as err:
print(str(err))
print_usage()
sys.exit(1)
for opt, arg in opts:
if opt in ("-h", "--help"):
print_usage()
sys.exit(1)
elif opt in ("-q", "--query"):
print(dictMgr.query(str(arg)))
else:
assert False, "unhandled option"
if __name__ == "__main__":
main()
# Youdao API setting:
# You can get the API Key & Keyfrom at "http://fanyi.youdao.com/openapi"
[youdao]
key=########
keyfrom=####
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment