看着学吧:我就不多解释了,主要看注释就差不多了。
至于模块安装有疑问的话,可以留言在这里,我会尽力解答。
# author: rexora
# date: Sept 25 2014
import httplib2
from urllib.parse import quote
from bs4 import BeautifulSoup
from sys import argv
import sys
import time
class Timer:
def __enter__(self):
self.start = time.time()
def __exit__(self, *args):
time_len = time.time() - self.start
if time_len != 0:
print('\n * * * 查询用了{:.2f}秒. * * * '.format( time_len + 0.8))
# 加0.8秒是因为我认为程序进入需要时间,这样可以让timer显得更准确。
def youdao_en2ch(word):
url = 'http://dict.youdao.com/search?q={}&keyfrom=dict.index'.format(word)
_, resp = httplib2.Http("g:/.cache").request(url)
content = resp.decode('utf-8')
soup = BeautifulSoup(content)
div_trans = soup.select('.trans-container') # if it's type, it'll only have less than 10 containers.
result = []
if len(div_trans) > 6:
div = div_trans[0]
for li in div.find_all('li'):
print(li.string)
result.append(str(li.string))
return (1, word, result) # 用1表示这时来自en2ch,2表示ch2en, this is a query containing 3 items
else:
try:
typo = soup.select('.error-typo')[0]
right_spell = typo.find('a').string
print('你要找的是不是"{}" ?'.format(right_spell))
except IndexError:
print('提示: 请仔细检查你的拼写,我没有找到这个词。')
def youdao_ch2en(word):
url = 'http://dict.youdao.com/search?le=eng&q={}&keyfrom=dict.top'.format(quote(word))
_, resp = httplib2.Http("g:/.cache").request(url)
content = resp.decode('utf-8')
soup = BeautifulSoup(content)
div_trans = soup.select('.trans-container')
if len(div_trans) > 3:
result = []
div = div_trans[0]
for branch in div.select('.wordGroup'):
part_of_speech = branch.find('span')
if part_of_speech.string != None:
print(part_of_speech.string, end = ' ')
for meaning in branch.find_all('a'):
print(meaning.string, end = '; ')
result.append(str(part_of_speech.string)+' '+'; '.join([str(i.string) for i in branch.find_all('a')]))
print()
return(2, word, result)
else:
print('提示: 请仔细检查你输入的内容,我没有找到这个词。')
def steal(query):
if query != None:
word = query[1]
result = ' '.join(query[2])
if query[0] == 1:
with open('g:/yod/yod-en2ch.txt','a',encoding='utf-8') as f:
print(word+'***'+result, file = f)
if query[0] == 2:
with open('g:/yod/yod-ch2en.txt','a',encoding='utf-8') as f:
print(word+'***'+result,file = f)
def input_detect():
word = ' '.join(argv[1:])
if word == '':
return # 如果word是空,则直接退出这个函数,然后进入while True里面的循环。
test = ''.join(argv[1:]).strip('\'')
is_eng = True
if quote(test) != test:
is_eng = False
if is_eng == True:
steal(youdao_en2ch(word))
else:
steal(youdao_ch2en(word))
if __name__ == '__main__':
with Timer():
print()
input_detect()
while True:
word = input('\n>>>')
with Timer():
argv = ['_', word]
print()
input_detect()