Home Backend Development Python Tutorial Use Python to get word translations from Youdao Dictionary webpage

Use Python to get word translations from Youdao Dictionary webpage

Jul 22, 2016 am 08:56 AM
python translate

Get the Chinese explanation of a word from the Youdao Dictionary web page.

import re
import urllib

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

Copy after login

I will share with you a command line version

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date  : 2014-04-03 21:12:16
# @Function: 有道翻译命令行版
# @Author : BeginMan

import os
import sys
import urllib
import urllib2
reload(sys)
sys.setdefaultencoding("utf-8")
import simplejson as json
import platform
import datetime

API_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+'&#63;'+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()
Copy after login

That’s all the content of this article, I hope you all like it

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Don't worry about watching movies without subtitles! Xiaomi announces the launch of Xiaoai Translation real-time subtitles for Japanese and Korean translation Don't worry about watching movies without subtitles! Xiaomi announces the launch of Xiaoai Translation real-time subtitles for Japanese and Korean translation Jul 22, 2024 pm 02:11 PM

According to news on July 22, today, the official Weibo of Xiaomi ThePaper OS announced that Xiaoai Translation has been upgraded. Real-time subtitles have been added to Japanese and Korean translations, and subtitle-free videos and live conferences can be transcribed and translated in real time. Face-to-face simultaneous interpretation supports translation into 12 languages, including Chinese, English, Japanese, Korean, Russian, Portuguese, Spanish, Italian, French, German, Indonesian, and Hindi. The above functions currently only support the following three new phones: Xiaomi MIX Fold 4 Xiaomi MIX Flip Redmi K70 Extreme Edition It is reported that in 2021, Xiao Ai’s AI subtitles will be added to Japanese and Korean translations. AI subtitles use Xiaomi’s self-developed simultaneous interpretation technology to provide a faster, more stable and accurate subtitle reading experience. 1. According to the official statement, Xiaoai Translator can not only be used in audio and video venues

How to download deepseek Xiaomi How to download deepseek Xiaomi Feb 19, 2025 pm 05:27 PM

How to download DeepSeek Xiaomi? Search for "DeepSeek" in the Xiaomi App Store. If it is not found, continue to step 2. Identify your needs (search files, data analysis), and find the corresponding tools (such as file managers, data analysis software) that include DeepSeek functions.

How do you ask him deepseek How do you ask him deepseek Feb 19, 2025 pm 04:42 PM

The key to using DeepSeek effectively is to ask questions clearly: express the questions directly and specifically. Provide specific details and background information. For complex inquiries, multiple angles and refute opinions are included. Focus on specific aspects, such as performance bottlenecks in code. Keep a critical thinking about the answers you get and make judgments based on your expertise.

How to search deepseek How to search deepseek Feb 19, 2025 pm 05:18 PM

Just use the search function that comes with DeepSeek. Its powerful semantic analysis algorithm can accurately understand the search intention and provide relevant information. However, for searches that are unpopular, latest information or problems that need to be considered, it is necessary to adjust keywords or use more specific descriptions, combine them with other real-time information sources, and understand that DeepSeek is just a tool that requires active, clear and refined search strategies.

How to program deepseek How to program deepseek Feb 19, 2025 pm 05:36 PM

DeepSeek is not a programming language, but a deep search concept. Implementing DeepSeek requires selection based on existing languages. For different application scenarios, it is necessary to choose the appropriate language and algorithms, and combine machine learning technology. Code quality, maintainability, and testing are crucial. Only by choosing the right programming language, algorithms and tools according to your needs and writing high-quality code can DeepSeek be successfully implemented.

How to use deepseek to settle accounts How to use deepseek to settle accounts Feb 19, 2025 pm 04:36 PM

Question: Is DeepSeek available for accounting? Answer: No, it is a data mining and analysis tool that can be used to analyze financial data, but it does not have the accounting record and report generation functions of accounting software. Using DeepSeek to analyze financial data requires writing code to process data with knowledge of data structures, algorithms, and DeepSeek APIs to consider potential problems (e.g. programming knowledge, learning curves, data quality)

The Key to Coding: Unlocking the Power of Python for Beginners The Key to Coding: Unlocking the Power of Python for Beginners Oct 11, 2024 pm 12:17 PM

Python is an ideal programming introduction language for beginners through its ease of learning and powerful features. Its basics include: Variables: used to store data (numbers, strings, lists, etc.). Data type: Defines the type of data in the variable (integer, floating point, etc.). Operators: used for mathematical operations and comparisons. Control flow: Control the flow of code execution (conditional statements, loops).

Magically modified 'Black Myth: Wukong ' to defeat Midjourney. This AI drawing tool is amazing. Magically modified 'Black Myth: Wukong ' to defeat Midjourney. This AI drawing tool is amazing. Aug 23, 2024 pm 09:42 PM

When AI Ideograms compete for realism and artistic sense, Ideogram has opened up a tricky track: it can accurately generate text on pictures, and the fonts and layouts are beautiful. This demand is not niche. Generate posters and illustrations with one click without using P-pictures. It can save a lot of trouble and is very suitable for ordinary people who know nothing about design. We previously wrote about version 1.0 of Ideogram. On August 21st, version 2.0 came. The realism is better, the posters are more designed, and the special skill of text is also stronger. You may have never heard of it. This is an AI product developed by former Google employees. It has many shortcomings, but the longboard can "overtake" Midjourney in corners. Directions https://ideogram.ai/A

See all articles