◎软件环境:
◎功能描述:
生活工作中,我们阅读古籍,经典看到字词或生僻字理解不了的时候,都会去查阅字典,汉典这个网站提供的内容就很丰富,包括字源字形、说文解字、康熙字典等解释都有。通过使用Alfred workflow调用汉典接口查询,可以省去打开网站输入搜索的过程,节省了些许时间。
◎实现思路:
通过requests去调用汉典的查询接口,bs4去抓取返回页面元素获取词的解释,调用alfred-workflow框架功能,想看词的详解按回车即可跳转到web页面,按shift键可以预览网页内容,按shift + enter键汉字发音。不好的地方就是接口或者页面元素变了,就得改下代码,当然还有更懒的方法,直接使用aflred的Web search的功能就行了。
#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
import sys
import requests
from bs4 import BeautifulSoup, Tag
from workflow import Workflow3
reload(sys)
sys.setdefaultencoding('utf-8')
def main(wf):
import urllib
if not wf.args:
return
word = wf.args[0].strip()
# 转成URL编码格式
if not isinstance(word, unicode):
word = word.decode('utf8')
word_u = urllib.quote(str(word))
url = "https://www.zdic.net/hans/{}".format(word_u)
resp = requests.request("POST", url)
resp.raise_for_status()
#如“国”不能查询,原因是没有去掉换行符。
#soup = BeautifulSoup(resp.content, "html.parser")
soup = BeautifulSoup(resp.content.replace("'u'\n'", ' ').replace('\r', '').replace('\n',''), "html.parser")
# 获取词解释
texts = []
sp = soup.find_all("span", attrs={"class": "dicpy"})
pinyin = sp[0].next_element
try:
#ol = [span.find_parent().next_sibling.select('li') for span in sp]
explain = sp[0].find_parent().next_sibling
#[s.extract() for s in explain('span')]
ol = explain.select('li')
if ol:
texts = [li.get_text("", strip=True) for li in ol]
else:
pl = [span.find_parent().next_sibling.select('p') for span in sp]
texts = [p.get_text("", strip=True) for p in pl[0]]
except AttributeError:
# 'NavigableString' object has no attribute 'attrs'
pass
# 调用Aflred-workflow库
count = 1
if texts:
for word in texts:
if word and count < 10:
img = 'icon/number_' + str(count) + '.png'
if count == 1:
wf.add_item(title=word, subtitle='拼音:' + pinyin,
arg=resp.url, valid=True, icon=img)
else:
wf.add_item(title=word, arg=resp.url, valid=True, icon=img)
count += 1
else:
title = '对方不按套路出牌,我也没办法了>0.0<...'
subtitle = '请按回车直接跳转到站内页面查看解释:)'
arg = resp.url
wf.add_item(
title=title, subtitle=subtitle, arg=arg,
valid=True, icon='icon.png')
wf.send_feedback()
if __name__ == '__main__':
wf = Workflow3()
sys.exit(wf.run(main))◎效果展示:
◎下载地址:https://github.com/anzhihe/Efficient-office/tree/master/ancient-chinese-zdic
参考:

为啥安装了豆瓣搜索的在Alfred4.0.9版本,但是输入关键词以后空格再键入搜索内容以后自动跳转去什么谷歌搜索去了,哪里设置出问题了吗?还是这个豆瓣搜索在新版本里不能用了?
@明天会秃头吗 你keywords没有打全吧,我这用没事呀