命令行实现英汉汉英词典

2 篇文章 0 订阅
2 篇文章 0 订阅

看着学吧:我就不多解释了,主要看注释就差不多了。

至于模块安装有疑问的话,可以留言在这里,我会尽力解答。

# 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()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值