使用Python從有道詞典網頁擷取單詞翻譯,python有道

來源:互聯網
上載者:User

使用Python從有道詞典網頁擷取單詞翻譯,python有道

從有道詞典網頁擷取某單詞的中文解釋。

import reimport urllibword=raw_input('input a word\n') url='http://dict.youdao.com/search?q=%s'%word content=urllib.urlopen(url) pattern=re.compile("</h2.*?</ul>",re.DOTALL) result=pattern.search(content.read()).group()pattern2=re.compile('<li>.*?</li>')for i in pattern2.findall(result):  print i.strip('<li>').strip('</li>').decode('utf-8')

再給大家分享一個命令列版的

#!/usr/bin/env python# -*- coding: utf-8 -*-# @Date  : 2014-04-03 21:12:16# @Function: 有道翻譯命令列版# @Author : BeginManimport osimport sysimport urllibimport urllib2reload(sys)sys.setdefaultencoding("utf-8")import simplejson as jsonimport platformimport datetimeAPI_KEY = '******'KEYFORM = '******'  def GetTranslate(txt):  url = 'http://fanyi.youdao.com/openapi.do'  data = {  'keyfrom': KEYFORM,  'key': API_KEY,  'type': 'data',  'doctype': 'json',  'version': 1.1,  'q': txt  }  data = urllib.urlencode(data)  url = url+'?'+data  req = urllib2.Request(url)  response = urllib2.urlopen(req)  result = json.loads(response.read())  return result  def Sjson(json_data):  query = json_data.get('query','')        # 查詢的文本  translation = json_data.get('translation','')  # 翻譯  basic = json_data.get('basic','')        # basic 列表  sequence = json_data.get('web',[])       # 片語清單  phonetic,explains_txt,seq_txt,log_word_explains = '','','',''    # 更多釋義  if basic:    phonetic = basic.get('phonetic','')     # 音標    explains = basic.get('explains',[])     # 更多釋義 列表    for obj in explains:      explains_txt += obj+'\n'      log_word_explains += obj+','    # 句子解析  if sequence:    for obj in sequence:      seq_txt += obj['key']+'\n'      values = ''      for i in obj['value']:        values += i+','      seq_txt += values+'\n'      print_format = '*'*40+'\n'  print_format += u'查詢對象: %s [%s]\n' %(query,phonetic)    print_format += explains_txt  print_format += '-'*20+'\n'+seq_txt  print_format += '*'*40+'\n'  print print_format  choices = raw_input(u'是否寫入單詞本,回複(y/n):')  if choices in ['y','Y']:    filepath = r'/home/beginman/pyword/%s.xml' %datetime.date.today()    if (platform.system()).lower() == 'windows':      filepath = r'E:\pyword\%s.xml' %datetime.date.today()    fp = open(filepath,'a+')    file = fp.readlines()    if not file:      fp.write('<wordbook>\n')      fp.write(u"""  <item>\n  <word>%s</word>\n  <trans><![CDATA[%s]]></trans>\n  <phonetic><![CDATA[[%s]]]></phonetic>\n  <tags>%s</tags>\n  <progress>1</progress>\n  </item>\n\n""" %(query,log_word_explains,phonetic,datetime.date.today()))    fp.close()    print u'寫入成功.'def main():  while True:    txt = raw_input(u'請輸入要查詢的文本:\n')    if txt:      Sjson(GetTranslate(txt))if __name__ == '__main__':  main()

以上就是本文的所有內容了,希望大家能夠喜歡

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.