#!/usr/bin/env python
# ----------------------------------------------------------------------------
# "THE BEER-WARE LICENSE" (Revision 42):
# <terry.yinzhe@gmail.com> wrote this file. As long as you retain this notice you
# can do whatever you want with this stuff. If we meet some day, and you think
# this stuff is worth it, you can buy me a beer in return to Terry Yin.
#
# The idea of this is borrowed from <mort.yao@gmail.com>'s brilliant work
# https://github.com/soimort/google-translate-cli
# He uses "THE BEER-WARE LICENSE". That's why I use it too. So you can buy him a
# beer too.
# ----------------------------------------------------------------------------
'''
This is a simple, yet powerful command line translator with google translate
behind it. You can also use it as a Python module in your code.
'''
import re
import json
from textwrap import wrap
try:
import urllib2 as request
from urllib import quote
except:
from urllib import request
from urllib.parse import quote
class Translator:
def __init__(self, to_lang, from_lang='auto'):
self.from_lang = from_lang
self.to_lang = to_lang
def translate(self, source):
self.source_list = wrap(source, 1000, replace_whitespace=False)
return ' '.join(self._get_translation_from_google(s) for s in self.source_list)
def _get_translation_from_google(self, source):
json5 = self._get_json5_from_google(source)
translation = ''
for sentence in json.loads(json5)['sentences']:
translation += sentence['trans']
return translation
def _get_json5_from_google(self, source):
escaped_source = quote(source, '')
headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_6_8) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.168 Safari/535.19'}
req = request.Request(
url="http://translate.google.com/translate_a/t?client=p&ie=UTF-8&oe=UTF-8"
+"&sl=%s&tl=%s&text=%s" % (self.from_lang, self.to_lang, escaped_source)
, headers = headers)
r = request.urlopen(req)
return r.read().decode('utf-8')
def main(defvals=None):
import argparse
import sys
import locale
if defvals is None:
defvals = {'f':'auto', 't':'zh'}
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('texts', metavar='text', nargs='+',
help='a string to translate(use "" when it\'s a sentence)')
parser.add_argument('-t', '--to', dest='to_lang', type=str, default=defvals['t'],
help='To language (e.g. zh, zh-TW, en, ja, ko). Default is '+defvals['t']+'.')
parser.add_argument('-f', '--from', dest='from_lang', type=str, default=defvals['f'],
help='From language (e.g. zh, zh-TW, en, ja, ko). Default is '+defvals['f']+'.')
args = parser.parse_args()
translator= Translator(from_lang=args.from_lang, to_lang=args.to_lang)
for text in args.texts:
translation = translator.translate(text)
if sys.version_info.major == 2:
translation =translation.encode(locale.getpreferredencoding())
sys.stdout.write(translation)
sys.stdout.write("\n")
if __name__ == "__main__":
main()
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
资源分类:Python库 所属语言:Python 资源全名:translate-1.0.8.tar.gz 资源来源:官方 安装方法:https://lanzao.blog.csdn.net/article/details/101784059
资源详情
资源评论
资源推荐
收起资源包目录
translate-1.0.8.tar.gz (5个子文件)
translate-1.0.8
PKG-INFO 3KB
test
testTranslate.py 3KB
translate.py 3KB
setup.py 1KB
translate 1KB
共 5 条
- 1
挣扎的蓝藻
- 粉丝: 14w+
- 资源: 15万+
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
最新资源
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0