最近看了看python,写写小脚本确实感觉很方便,今天尝试写了个简易的在线词典,为了平时查字典方便点,暂时仅仅实现了很简单的功能,效果:
仅仅爬下了中间那段html代码,自己用已经足够了,至少不用每天在网页上查了。
完整代码:
#!/usr/bin/python
import re;
import urllib;
def getHtml (url):
page = urllib.urlopen (url);
return page.read();
def getTranslation (html):
try:
re1 = r'(?<=<div class="trans-container">).+?(?=</div>)';
cre1 = re.compile (re1, re.S);
s2 = re.search (cre1, html).group (0);
re2 = r'(?<=<li>).+?(?=</li>)';
cre2 = re.compile (re2, re.S);
return re.findall (cre2, s2);
except Exception, e:
print e;
return ['didn\'t find'];
if __name__ == '__main__':
url = 'http://dict.youdao.com/search?q=%s';
while True:
print '>>>', ;
word = raw_input ();
word = word.strip ();
if not word:
continue;
if word == 'exit()':
break;
html = getHtml (url % word);
trans = getTranslation (html);
for ss in trans:
print ss;