Apr.6 更新:修正一处elif写成if的bug;增加ctrl-c强制停止的支持;增加对不填字符个数的用处的说明
最近“Draw Something”很火,我也玩了几次。碰到过靠谱的搭档,也碰到过很不靠谱的搭档。当然我自己也属于不靠谱一类,哈哈。
碰到的不靠谱的人多了,猜个词就费劲了。试词语让人很不爽。
所以就想写个Python脚本干这事。
首先想到了我这边对备选的字符进行排列,然后找个网络词典的接口来进行查验。
网上能搜到的在线词典的接口比较少,有dict.cn, iciba.cn和dict.qq.com的。其实我本人想用iciba的来着,不过貌似现在不能用了。最后选择了qq的词典。json返回值,我很喜欢。
刚才找了下google translate的接口,确实有。不过1M字符=20刀的价格真是伤不起。
接口搞定,就差对所有字符排列组合了。最后俺选用了itertools.permutations方法。这个方法比较傻,对所有字符进行穷举排列;如果哪位同学有更好的算法,欢迎不吝赐教:)
好了,不多说了,上代码
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: weibo @SeganW
"""
from __future__ import unicode_literals
import urllib
import json
import itertools
import sys
def query(word):
con=None
try:
#由于google translate接口收费,而且非常的贵;
#词霸的接口现在好像用不了了,不知道谁知道新地址
#网上能找到能使用的就剩qq词典;词典结果不是很理想;
#比如有些单词不在本地词典中,而网络释义的结果有非常的不可信,只能退而求其次,把所有网络释义都标记上了,大家自行鉴别
con=urllib.urlopen('http://dict.qq.com/dict?q={}'.format(word))
resp=con.read()
except Exception as e:
print '[error] get {!r} definition failed: {}'.format(word,e)
if con:
con.close()
return None
resp_json=json.loads(resp)
if resp_json.get('err'):
return None
elif resp_json.get('lang') != 'eng':
return None
else:
descs=[]
if resp_json.get('local'):
try:
loc_desc=resp_json['local'][0]['des']
except KeyError:
return None
for des in loc_desc:
try:
p_type=des['p']
except KeyError as ke:
return None
if p_type == 'n.':
descs.append(des['d'])
elif resp_json.get('netdes'):
for net_desc in resp_json.get('netdes'):
net_word=net_desc.get('word')
if net_word and net_word.lower()==word.lower():
try:
descs.append('网络释义:{}'.format(net_desc['des'][0]['d']))
except KeyError:
continue
else:
return None
else:
return None
if descs:
result= '{} : {}'.format(word,';'.join(descs)).encode(sys.getfilesystemencoding())
print result
else:
result=None
return result
def guess(char_str,num=None):
if not num:
num=len(char_str)
assert isinstance(char_str,str), 'not a string'
#非常傻的穷举方法,有好的算法的同学请不吝赐教~
pmt=itertools.permutations(char_str,r=num)
result=[]
for i in pmt:
word=''.join(i)
#print 'Guessing word {!r}'.format(word)
guess_result=query(word)
if guess_result:
result.append(guess_result)
return result
if __name__ == '__main__':
args=sys.argv
if len(args)==2:
charstr= args[1]
num=None
elif len(args)==3:
charstr= args[1]
num=int(args[2])
else:
raise SystemExit('usage: drawsomthing.py charstr [num]')
print """友情提醒:由于QQ词典网络释义和部分解释不准确,请自行辨别\n开始查询..."""
try:
guess(charstr,num)
except KeyboardInterrupt:
print '已强制退出'
else:
print "查询结束"
运行的命令行就是
drawsomething.py char_str num
char_str为程序显示的乱序字符串,把让你拆的所有字符串起来做一个字符串
num是程序让你猜的单词包含的字符个数;可不填,这样就变成python版词典了:)
刚才写这篇文章的时候发现有道词典已经做好了更先进的工具(毕竟人家有完善的词库,俺这只是个小python脚本~),大家如果真的要用的话,就去用它的吧,地址在这里。






