為什么寫這個程序,為什么不給這個程序配備gui?原因很簡單,因為我是一個命令行控,Linux習慣了不習慣了鼠標,總覺得點著不如敲命令快,各位在看這篇文章就說明和本人有相同的愛好.這個用python寫的翻譯工具是通過google來實現的,由于google返回的數據不是很規(guī)范(或者說我沒有找到規(guī)律),現在前三項能正常顯示(源詞,翻譯結果,和漢語拼音).下面的詞性和其他釋義可能不同,見諒,望大神可以指點下小弟和幫小弟完善,這里趕緊不盡.
好了不費話了,下面放代碼:
#!/usr/bin/env python# -*-coding:utf8 -*-'''#=============================================================================# FileName: translate.py# Desc: To translate with zh to en or en2zh# Author: cold# Email: wh_linux@126.com# HomePage: http://www.linuxzen.com# Version: 0.0.1# LastChange: 2012-04-23 23:04:08# History:#============================================================================='''import urllibimport urllib2from sys import argv,exitimport re# 顯示幫助信息def helpinfo():print '''Usage: pytran {zh2en|en2zh} content'''# 格式化輸出def formatresult(result,srclang):resu = result.split('[[')if (srclang=='en2zh' or srclang == 'zh2en'):firstre = resu[1].replace('[','').replace(']','').split('"')print '源詞:',firstre[3]print '結果:',firstre[1]if (srclang=='zh2en'):piny = firstre[7]else:piny = firstre[5]print '拼音:',pinyif(srclang=='zh2en'):secresu=resu[2].replace('"','').split('[')else:secresu = resu[2].replace('"', '').split('[')print '詞性:',secresu[0].replace(',','')print '其他釋義:'for i in ''.join(secresu[1].split(']')).split(','):print i# 獲取命令行參數try:srclang = argv[1]except:helpinfo()exit(1)try:cont = argv[2]except:helpinfo()exit(2)# 判斷翻譯目標語言用來確定傳送參數if(srclang == 'zh2en'):data=urllib.urlencode({'client':'t', 'text':cont,'hl':'zh-CN','tl':'en','multires':'1','prev':'btn','ssel':'0','sc':'1'})elif(srclang == 'en2zh'):data=urllib.urlencode({'client':'t', 'text':cont,'hl':'zh-CN', 'sl':'en','tl':'zh-CN','multires':'1', 'prev':'btn','ssel':'0','sc':'1'})else:helpinfo()# 打開google翻譯內容url = 'http://translate.google.cn/translate_a/t'req =urllib2.Request(url,data)req.add_header("User-Agent", "Mozilla/5.0+(compatible;+Googlebot/2.1;++http://www.google.com/bot.html)")fd = urllib2.urlopen(req)result = fd.read()# 格式化輸出formatresult(result, srclang)fd.close()
為了更方便的使用我們把這個腳本命名位pytranslate,放到/usr/bin下,并賦予執(zhí)行權限:
chmod +x /usr/bin/pytranslate
然后我們就可以使用它進行翻譯了: 翻譯英文到中文:
pytranslate en2zh extent源詞: extent結果: 程度拼音: Chéngdù詞性: 名詞其他釋義:程度范圍幅度規(guī)模度地步廣度長度面長短份兒界en翻譯中文到英文pytranslate zh2en 中國源詞: 中國結果: China拼音: Zhōngguó詞性: 名詞其他釋義:Chinazh-CN
新聞熱點
疑難解答