stone2083

命令行下翻译工具

接上文,继续show下我命令行下的工具--翻译脚本
(利用了google 翻译 json api:http://translate.google.cn/translate_a/t?client=t&text=%s&hl=zh-CN&sl=%s&tl=%s

特性:
1. 自动识别中翻英/英翻中
2. 翻译

涉及技术:
1. python
2. urllib
3. json
4. re

截图:


对应代码:
 1 '''
 2 Created on 2010-11-28
 3 
 4 @author: stone
 5 '''
 6 import json
 7 import re
 8 import sys
 9 import urllib2
10 import types
11 
12 res = 'http://translate.google.cn/translate_a/t?client=t&text=%s&hl=zh-CN&sl=%s&tl=%s'
13 agent = 'Mozilla / 5.0 (X11; U; Linux i686; en - US) AppleWebKit / 534.7 (KHTML, like Gecko) Chrome / 7.0.517.44 Safari / 534.7'
14 
15 def get_data(text, sl='en', tl='zh-CN'):
16     req = urllib2.Request(res % (urllib2.quote(text), sl, tl))
17     req.add_header('user-agent', agent)
18     content = urllib2.urlopen(req).read()
19     return json.loads(to_standard_json(content))
20 
21 def show(data):
22     #step1
23     print u'翻译:\n  %s' % (data[4][0][0])
24     #step2
25     if types.ListType == type(data[1]):
26         print u'\n字典:'
27         for word in data[1]:
28             print word[0]
29             if len(word) > 1:
30                 for i, w in enumerate(word[1]):
31                     print '  %s.%s' % (i + 1, w) 
32 
33 def to_standard_json(json):
34     p = re.compile(r',([,\]])')
35     while(p.search(json)):
36         json = p.sub(lambda m:',null%s' % (m.group(1)), json)
37     return json
38 
39 def contains_cn(text):
40     for c in text:
41         if ord(c) > 127:
42             return True
43     return False
44 
45 if __name__ == '__main__':
46     if not len(sys.argv) == 2 or not sys.argv[1].strip():
47         print 'Useage:translate.py word'
48         sys.exit()
49     word = sys.argv[1].strip()
50     if contains_cn(word):
51         show(get_data(word, 'zh-CN''en'))
52     else:
53         show(get_data(word, 'en''zh-CN'))


posted on 2011-04-17 19:49 stone2083 阅读(2482) 评论(3)  编辑  收藏 所属分类: python

Feedback

# re: 命令行下翻译工具 2011-04-18 21:08 西瓜影院

一直不用 命令翻译的说
用的都是工具 在你这学习了  回复  更多评论   

# re: 命令行下翻译工具 2013-05-06 10:02 gftgh

[CustomFont]
Texture=Textures/紫钻1.tga
CellX=15
CellY=12
Text="123456"  回复  更多评论   

# re: 命令行下翻译工具 2014-01-11 15:54 张启杰

魺癍怞?湄嗚<髖?{?貱洠癍?0钳镊}R蠹麅磞=M??鲽+□%齨.來$枙漇?dMu??Uv軇鏚珶>焬碍}揯-,$猊霨誕??霔no'SA潸駔?仛 秸r懪娃?橮0?鞅杏7鳦T*U(o廦Xr鐉?nX帅)??罤^?=y黝斾y凗蜃舯??w礹澫脜貃2x囔?X<qw8?仿
$A€]襟j咭痯闃好驺9瘝@蚓q逋>a枢籡+薁濚睹 F?徨t€隰宽|?寕鮆?  回复  更多评论   


只有注册用户登录后才能发表评论。


网站导航: