“你画我猜”(draw something)单词猜测工具 – 升级版

前几天写的“你画我猜”(draw something)单词猜测工具,最后提到了有道已经做了相关工具。既然有大树了,俺们就可以直接乘凉了~

使用有道网页版的改进版本来了:直接发送查询请求然后对返回结果格式化就搞定了,非常easy:)(需要用到lxml模块)

 
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@author: Sina Weibo @SeganW
"""
from __future__ import unicode_literals
import urllib
import lxml.html as lh
import sys

def query(char_str,num=None):
    if not None:
        num=len(char_str)
    con=None
    resp=None
    try:
        con=urllib.urlopen('http://dict.youdao.com/drawsth?letters={}&length={}'.format(char_str,num))
        resp=con.read()
    except Exception as e:
        if con:
            con.close()
        raise SystemExit('[error] guess request failed: {}'.format(e))
    doc=lh.document_fromstring(resp)
    words=[i.text_content().lower() for i in doc.xpath("//span[@class='word']")]
    translates=[i.text_content() for i in doc.xpath("//div[@class='trans']")]
    return zip(words,translates)

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]')
    results=query(charstr,num)
    if results:
        for sub_result in results:
            print '{}:\t{}'.format(*sub_result)
    else:
        print "No results found:("

使用方法不变:

运行的命令行就是

drawsomething_updated.py char_str [num]

char_str为程序显示的乱序字符串,把让你拆的所有字符串起来做一个字符串
num是程序让你猜的单词包含的字符个数;可不填,这样就变成python版词典了:)

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s