Skip to content

Commit

Permalink
增加配置文件,增加海词词典
Browse files Browse the repository at this point in the history
  • Loading branch information
liberize committed Jul 13, 2015
1 parent 4c0678e commit 3519153
Show file tree
Hide file tree
Showing 17 changed files with 731 additions and 412 deletions.
36 changes: 23 additions & 13 deletions Dict - Lookup Word/actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,14 @@
import os
import re
import cndict
import plistlib
import json

if len(sys.argv) != 2:
sys.exit(1)
from cache import Cache
from alfredplist import AlfredPlist


def get_keyword():
plist = plistlib.readPlist(os.path.abspath('./info.plist'))
for item in plist['objects']:
if 'keyword' in item['config']:
return item['config']['keyword']
if len(sys.argv) != 2:
sys.exit(1)


def restore(arg):
Expand All @@ -29,17 +26,30 @@ def shell_exec(cmd, arg, escape=False):
os.system(cmd.format("'{}'".format(arg.replace("'", "\\'"))))


match = re.match(r'^(:.*?) ([@|>]) (.*?)$', sys.argv[1])
plist = AlfredPlist()
plist.read(os.path.abspath('./info.plist'))

match = re.match(r'^:(.*?) ([@|>]) (.*?)$', sys.argv[1])
if match:
keyword = get_keyword()
if keyword:
restore('{} {}'.format(keyword, match.group(1)))
command = match.group(1).strip()
if command == 'clean':
base_dir = os.path.expanduser('~/Library/Caches/com.runningwithcrayons.Alfred-2/Workflow Data/')
dict_cache = Cache(os.path.join(base_dir, plist.get_bundleid()))
dict_cache.clean()
elif command == 'config':
shell_exec('open {}', os.path.abspath('./config.json'))
elif command == 'update':
config_data = open(os.path.abspath('./config.json')).read()
config = json.loads(re.sub(r'//.*', '', config_data))
plist.set_keyword(config['keyword'])
plist.set_keymap(config['keymap'])
plist.write(os.path.abspath('./info.plist'))
else:
match = re.match(r'^(.*?) @ (.*?) (\| (.*) )?([@|>]) (.*?)$', sys.argv[1])
if match:
word, dictionary, _, item, operator, command = match.groups()
if operator == '@':
keyword = get_keyword()
keyword = plist.get_keyword()
if keyword:
if item:
new_word = cndict.extract(dictionary, word, item)
Expand Down
75 changes: 75 additions & 0 deletions Dict - Lookup Word/alfredplist.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import re
import plistlib
import cndict


class AlfredPlist(object):
def __init__(self):
self.__modifier_map = {
0: 'none',
524288: 'alt',
262144: 'ctrl',
131072: 'shift',
1048576: 'cmd',
8388608: 'fn'
}
self.__plist = None
self.__base = None
self.__branches = {}

def read(self, path):
self.__plist = plistlib.readPlist(path)
for obj in self.__plist['objects']:
if 'keyword' in obj['config']:
self.__base = obj
uid = self.__base['uid']
for conn in self.__plist['connections'][uid]:
self.__branches[conn['destinationuid']] = [conn, None]
break
for uid, pair in self.__branches.iteritems():
for obj in self.__plist['objects']:
if uid == obj['uid']:
pair[1] = obj
break

def write(self, path):
if self.__plist:
plistlib.writePlist(self.__plist, path)

def get_keyword(self):
if self.__base:
return self.__base['config']['keyword']
return ''

def set_keyword(self, value):
if self.__base:
self.__base['config']['keyword'] = value

def get_keymap(self):
keymap = {}
for conn, child in self.__branches.values():
modifier = self.__modifier_map[conn['modifiers']]
match = re.search(r'[@|>] (\w+)"', child['config']['script'])
if match:
keymap[modifier] = match.group(1)
return keymap

def set_keymap(self, value):
keymap = value
for conn, child in self.__branches.values():
modifier = self.__modifier_map[conn['modifiers']]
if modifier in keymap:
child['config']['script'] = re.sub(r'(?<=[@|>] )\w+(?=")', keymap[modifier],
child['config']['script'])
if modifier != 'none':
dict_name = cndict.get_full_name(keymap[modifier])
conn['modifiersubtext'] = re.sub(r'(?<=in )\w+(?= dict)', dict_name,
conn['modifiersubtext'])

def get_bundleid(self):
if self.__plist:
return self.__plist['bundleid']
return ''
15 changes: 11 additions & 4 deletions Dict - Lookup Word/cndict/__init__.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,26 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import importlib
from utils import *


def _load_module(dictionary):
def get_full_name(dictionary):
dict_name_map = {
'sys': 'system',
'nj': 'oxford',
'ld': 'landau',
'yd': 'youdao',
'cb': 'iciba',
'bd': 'baidu',
'by': 'bing'
'by': 'bing',
'hc': 'dictcn'
}
module_name = dict_name_map.get(dictionary, dictionary) + 'dict'
return dict_name_map.get(dictionary, dictionary)


def _load_module(dictionary):
module_name = get_full_name(dictionary)
try:
return importlib.import_module('.' + module_name, __name__)
except ImportError:
Expand Down
15 changes: 15 additions & 0 deletions Dict - Lookup Word/cndict/__main__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys
import os

sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from cndict import lookup

if len(sys.argv) < 3:
print 'usage: python cndict <dict> <word>'
sys.exit(1)

result = lookup(*(sys.argv[1:]))
print '\n'.join(result)
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from utils import *


def lookup(word):
def lookup(word, *args):
params = {
'client_id': 'Gh4UZOrtK9cUba2MW4SuTS3T',
'q': word
Expand Down
92 changes: 92 additions & 0 deletions Dict - Lookup Word/cndict/bing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import urllib
import urllib2
import gzip
import re
import StringIO
from utils import *


def lookup(word, wap_page=True, *args):
params = {'q': word}
if wap_page:
params['view'] = 'wap'
url = 'http://dict.bing.com.cn/'
else:
url = 'http://www.bing.com/dict/search'
url = '{}?{}'.format(url, urllib.urlencode(params))
try:
request = urllib2.Request(url)
request.add_header('Accept-Encoding', 'gzip')
response = urllib2.urlopen(request)
data = response.read()
except:
raise DictLookupError('error to fetch data.')

if response.info().get('Content-Encoding') == 'gzip':
gzip_file = gzip.GzipFile(fileobj=StringIO.StringIO(data))
data = gzip_file.read()

result = []
is_eng = is_english(word)

if wap_page:
match = re.search(r'<div><b>.*?</b>{}<br />(.*?)<br />web\.<br />'.format(
r'.*?US:\[(.*?)\](.*UK:\[.*?\])?.*?'
if is_eng else
r'.*?'), data)
if match is None:
raise DictLookupError('failed to parse html.')

phonetic = match.group(1) if is_eng else ''
result.append('{}{}'.format(word, ' /{}/'.format(phonetic) if phonetic else ''))
definition = match.group(3 if is_eng else 1)
items = definition.replace('&nbsp;', '').replace('&bull;', '').split('<br />')
part = ''
for item in items:
match = re.match(r'^([a-z]+\.)$', item)
if match:
part = match.group(1)
continue
result.append('{} {}'.format(part, item))
else:
# no need to use BeautifulSoup, just extract definition from meta tag
match = re.search(r'<meta name="description" content="(.*?)"/>', data)
if match is None:
raise DictLookupError('failed to find meta tag.')
description = match.group(1)

match = re.match(r'^必应词典为您提供.*的释义,{},(.*); 网络释义: .*; $'.format(
r'美\[(.*?)\](,英\[.*?\])?'
if is_eng else
r'拼音\[(.*)\]'), description)
if match:
phonetic = match.group(1)
result.append('{}{}'.format(word, ' /{}/'.format(phonetic) if phonetic else ''))
items = match.group(3 if is_eng else 2).split('; ')
if is_eng:
for item in items:
if item != '':
result.append(item)
else:
for item in items:
match = re.match(r'([a-z]+\.) (.+)', item)
if match:
part = match.group(1)
for new_item in match.group(2).split('; '):
result.append('{} {}'.format(part, new_item))
return result


def extract(word, item):
if not is_english(word):
match = re.match(r'[a-z]+\. (.+)', item)
if match:
return match.group(1)


def get_url(word):
params = {'q': word}
return '{}?{}'.format('http://www.bing.com/dict/search', urllib.urlencode(params))
66 changes: 0 additions & 66 deletions Dict - Lookup Word/cndict/bingdict.py

This file was deleted.

Loading

0 comments on commit 3519153

Please sign in to comment.