python翻译(来源有道)

使用爬虫来制作一个简单的翻译的东西,翻译的来源是有道,可以实现从英文到中文,也可以从中文到英文。(其实就是爬取了有道的翻译信息)

翻译实例

E:\>python test.py
input the word you want to search:
are
are:
1:v. 是(be的第二人称单复数现在式)
2:n. 公亩
3:n. (Are)人名;(意、西、芬)阿雷

E:\>python test.py
input the word you want to search:
你好
你好:
1:hello;hi
from bs4 import BeautifulSoup
import bs4
import requests

def getHtmlText(url):
    try:
        r=requests.get(url,timeout=30)
        r.raise_for_status()
        r.encoding=r.apparent_encoding
        return r.text
    except:
        return ""

def parserPage(html):
    result=list()
    soup=BeautifulSoup(html,'html.parser')
    result=soup.find('div',attrs={'class':'trans-container'}).ul.strings #获取解释的字符串
    return result

def printTransResult(word,translist):
    print(word+':')
    count=0
    for tran in translist:
        if len(tran)>0:
            count+=1
            print('%d:%s'%(count,tran))

def main():
    keyword=input('input the word you want to search:\n')
    url='http://dict.youdao.com/w/'+keyword
    html=getHtmlText(url)
    tlt=parserPage(html)
    tlt=[i for i in tlt if i !='\n']
    printTransResult(keyword,tlt)

main()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容