$cat youdao.py
#encoding:utf8
import sys
import urllib2
from lxml import etree
import json
import urllib
from optparse import OptionParser
ua_header = {"User-Agent":
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36"}
#这个是有道的,为了查单个单词。这个最简单。
def getWordText(word):
url = "http://www.youdao.com/w/eng/"+word+"/#keyfrom=dict2.index"
# print "输入错误:\n如:\npython youdao 1 没有空格的单词\npython youdao 2 英文语句"
try:
request = urllib2.Request(url,headers=ua_header)
response = urllib2.urlopen(request)
htmldata = response.read()
#print "test:",htmldata
htmldata = etree.HTML(htmldata)
expression_xpath = "/html/body/div[1]/div[2]/div[1]/div[2]/div[2]/div[1]/div[2]/ul/li"
zh_text = htmldata.xpath(expression_xpath)
#print len(zh_text)
#print zh_text
if zh_text ==[]:
print "输入错误,请查看帮助"
for x in zh_text:
print x.text
except Exception as e:
print e
#从百度翻译获取的,对句子进行翻译,也可以单词,但是单词解释就详细。
def getSentenceText(s):
"""
s:你要输入的英文句子
"""
url = "http://fanyi.baidu.com/v2transapi/"
datadict = {"from":"en",
"to":"zh",
"query":None,
"simple_means_flag":'3',
}
datadict["query"] = s
formdata = urllib.urlencode(datadict)
try:
request = urllib2.Request(url,data=formdata,headers=ua_header)
response = urllib2.urlopen(request)
htmldata = response.read()
jsontext = json.loads(htmldata)
result = jsontext["trans_result"]["data"][0]["dst"]
if result ==None or result ==[]:
print "输入错误,请查看帮助"
print result
except Exception as e:
print "error:",e
#从命令行获取你的输入
def getOptions():
parser = OptionParser()
parser.add_option('-t','--type',type='string',action='store',dest='type',
help=u"输入类型,1 单词详解;2 语句翻译")
parser.add_option("-c",'--contents',type="string",action='store',dest="contents",
help=u"输入你的英文单词或者语句")
options,args = parser.parse_args()
return options
def main():
enter = getOptions()
t = enter.type
contents = enter.contents
if '1' in t:
print contents,"\n翻译如下:"
getWordText(contents)
elif '2' in t:
print contents,"\n翻译如下:"
getSentenceText(contents)
if __name__=="__main__":
main()
如何操作:
1.安装lxml库
(1) pip 方式:
pip install lxml
(2) ubuntu下:
apt-get install python-lxml
(3) centos下:
yum install python-lxml
2.程序是python2编写的,如下运行:
(1)获取帮助:
[root#]python youdao.py -h
Usage: youdao.py [options]
Options:
-h, --help show this help message and exit
-t TYPE, --type=TYPE 输入类型,1 单词详解;2 语句翻译
-c CONTENTS, --contents=CONTENTS
输入你的英文单词或者语句
(2) 查询单词:
[root#]python youdao.py -t 1 -c beautiful
beautiful
翻译如下:
adj. 美丽的
出色地
出色的
迷人的
迷人地
(3) 查询语句:
[root#] python youdao.py -t 2 -c "I love you,you love him,he loves her"
I love you,you love him,he loves her
翻译如下:
我爱你,你爱他,他爱她。
3.使用别名:
(1)在 ~/.bashrc最后一行添加如下:
alias fyi="/usr/bin/python /home/jokerzhang/scripts/fanyi/youdao.py -t"
(2)执行命令如下:
source 或 . .bashrc
(3) 这样就可以简化操作了:
fyi 1 -c hello