forked from hahaleyile/translateScripts
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.py
More file actions
40 lines (34 loc) · 1.34 KB
/
Main.py
File metadata and controls
40 lines (34 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import argparse
from typing import Iterator, NoReturn
from polyglot.detect import Detector
from polyglot.detect.base import UnknownLanguage
import CaiYun
import Google
def main(text: str, translator) -> NoReturn:
"""
print the translation to the stdout
:param translator: a class which to call translate function and get the result
:param text: source text
:return: none
"""
paragraphs: Iterator[str] = filter(lambda x: x, text.split('\n'))
for paragraph in paragraphs:
try:
detector = Detector(paragraph)
except UnknownLanguage:
print("无法检测源语言")
else:
language: str = detector.language.code
print(paragraph)
print(translator.translate([paragraph], language))
print(u"Detected source language: {}".format(detector.language.name))
if __name__ == '__main__':
translators = {"CaiYun": CaiYun.CaiYun(), "Google": Google.Google()}
parser = argparse.ArgumentParser(description="use translators to translate text")
parser.add_argument("text", type=str, help="the source text you want to translate")
parser.add_argument("-t", "--translator", type=str, default="Google",
choices=translators.keys(),
help="specify the translator you want to use (default: %(default)s)")
args = parser.parse_args()
text = args.text.replace('\n', ' ')
main(text, translators.get(args.translator))