#!/usr/bin/env python
#coding=utf-8

from xml.dom import minidom
import urllib, urllib2
import sys, os
import pygame
import prasexml

class ibword():
    def __init__(self, keyword):
        pygame.init() 
        self.path = os.path.abspath(os.path.join(os.getcwd(), __file__))
        self.path = os.path.dirname(self.path)   
        proxy=urllib2.ProxyHandler({'http': 'http://lk:2002@172.17.5.53:80'})
        opener=urllib2.build_opener(proxy)
        urllib2.install_opener(opener)        
        self.SEPARATE_LINE = '--------------------------------------------------------'     
        self.iCIBA_URL = "http://dict.cn/ws.php?"  
        self.key = keyword
        self.ps = ''
        self.pron = ''
	self.def00 = ''
        self.acceps = []
        self.sents = []
        self.iciba()
             
    def iciba(self):     
        #url = r'http://dict-co.iciba.com/api/dictionary.php?w=good'
	#http://dict.cn/ws.php?q=monday
        url = self.iCIBA_URL + urllib.urlencode({'q': self.key}, 'true')
        response = urllib2.urlopen(url)
        xml = response.read()
	xml = xml.decode('gbk')
	xml = xml.replace('encoding="GBK"', 'encoding="UTF-8"')
	xml = xml.encode('utf-8')
        #f = file('d:/002.xml', 'w')
        #f.write(xml)
        #f.close()
        #xml = prasexml.prasexml(xml)
        #xmldoc = minidom.parse(response)
        xmldoc = minidom.parseString(xml)
        Node = xmldoc.firstChild
        for n in Node.childNodes:
            #print n.nodeName
            if n.nodeName == 'key':
                self.key = n.firstChild.nodeValue
            if n.nodeName == 'pron':
                self.ps = n.firstChild.nodeValue
            if n.nodeName == 'audio':
                self.pron = n.firstChild.nodeValue
            if n.nodeName == 'def':
                self.def00 = n.firstChild.nodeValue			    
            if n.nodeName == 'pos':
                _pos = n.firstChild.nodeValue
                self.acceps.append([_pos, ''])    
            if n.nodeName == 'acceptation':
                _acceptation = n.firstChild.nodeValue
                if len(self.acceps) > 0 and self.acceps[-1][1] == '':
                    self.acceps[-1][1] = _acceptation
                else:
                    self.acceps.append(['', n.firstChild.nodeValue])        	
            if n.nodeName == 'sent':
                sent = []
                for m in n.childNodes:
                    sent.append(m.firstChild.nodeValue)
                if len(sent) > 0:
            	    self.sents.append(sent)

    def icibaTxt(self):
        txt = ''
        txt += "%s (%s)" % (self.key, self.ps) +'\r\n'
        #print word.pron
        txt += self.SEPARATE_LINE+'\r\n'

        for a in self.acceps:
            txt += a+'\r\n'
    
        txt += self.SEPARATE_LINE+'\r\n'    
        for b in self.sents:
            for c in b:
                if not c.startswith('http'):
                    txt += c+'\r\n'
            txt += self.SEPARATE_LINE+'\r\n'
            #print self.sents
            #print "End."
        return txt  
        
    def icibaHtml(self):
        _htm = '''
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h3><font color="Purple">%s [%s]</font>%s</h3>
%s
%s
</body>
</html>'''   
     
        htm_accps = ''
        htm_sents = ''
        htm_pron = ''
	_def00 = '<h5><font color="blue">%s</font></h5>'
        _pron = '<a href="#speaker"><IMG src="%s/speaker3.png"></a>'
        _accep = '<h5><font color="blue">%s %s</font></h5>'
        _sent_01 = '<h5><font color="Maroon">%s</font></h5>'
        _sent_02 = '<h5>%s</h5>'
        _sents = [_sent_01, _sent_02]
        if self.pron:
            htm_pron = _pron%(self.path)
        l = len(self.acceps)
        for i in range(l):
            htm_accps += _accep%(self.acceps[i][0], self.acceps[i][1])
        
	htm_def00 = _def00%(self.def00)
        for b in self.sents:
            i = 0
            for c in b:
                if not c.startswith('http'):
                    data = _sents[i%2]%(c)
                    htm_sents += data
                    i = i + 1
        htm = _htm%(self.key, self.ps, htm_pron, htm_def00, htm_sents)
        return htm          
            
    def icibaPron(self):
        '''http://res.iciba.com/resource/amp3/f/9/f97c5d29941bfb1b2fdab0874906ab82.mp3'''
	'''http://mp3.dict.cn/mp3.php?q=kfoxn'''
        if self.pron == '':
            return
        url = self.pron
	print url
        filenm = os.path.join(self.path, url[29:]+'.mp3')
        if not os.path.isfile(filenm):
            basedir = os.path.dirname(filenm)
            if not os.path.exists(basedir):
                os.makedirs(basedir)
            try:
                response = urllib2.urlopen(url)                
                #print response.getcode()
                data = response.read()
                if len(data) == 535:
                    raise urllib2.HTTPError(url=url, code=404, msg='404', hdrs=None, fp=None)
                f = file(filenm, 'wb')
                f.write(data)
                f.close()
                print "OK down."
            except urllib2.HTTPError, e:
                self.pron = ''
                print e.code
        
        if os.path.isfile(filenm):            
	    cmd = 'lame %s --decode'%filenm            
            os.popen(cmd).read()
	    filenm = filenm + '.wav'
	    print filenm
            self.playSound(filenm)

    def playSound(self, filenm):
        try:
            pygame.mixer.music.load(filenm)
        except:
            print "error"
            return    
            
        for i in range(2):
            if pygame.mixer.music.get_busy() == False:
                print 'is playing!'
                pygame.mixer.music.play()                                
        
if __name__ == '__main__':
    args = sys.argv[1:]
    if not args:
        word = ibword("good")
        #print word.icibaHtml()
	print len(word.icibaHtml())
        #word.icibaPron()
        #raw_input('wait')
    else:
        strword = ' '.join(args)     
        txt = icibaTxt(strword)
        print txt


Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐