Пример #1
0
 def write_tx(self, oldfile, newfile, reg, creg, des, lan, channel):
     if (not isWindows):
         f = open(oldfile)
     else:
         f = open(oldfile, encoding='UTF-8')
     line = f.readline()
     txd = ''
     while line:
         line = line.replace('\n', '')
         if (len(line) == 0):
             line = f.readline()
             continue
         originLine = line
         utils.printf('original:' + originLine)
         line = re.findall(reg, line)
         if (len(line) and line[0]):
             txc = self.translate(line[0], des, lan, channel)
             if (len(txc)):
                 originLine = re.sub(reg, creg.replace('content', txc),
                                     originLine)
             else:
                 utils.printf('translate fail:' + line)
         elif (reg == creg == r'text'):
             originLine = self.translate(originLine, des, lan, channel)
         else:
             utils.printf('skip: ' + originLine)
         originLine = self.fix_tx(originLine)
         utils.printf('translated:' + originLine)
         txd += originLine + '\n'
         utils.printf('-----')
         line = f.readline()
     f = open(newfile, 'w+')
     f.write(txd)
     f.close()
Пример #2
0
 def trans1(self, text, dest, src):
     s.get('https://aidemo.youdao.com/trans')
     data1 = {'q': text, 'from': 'Auto', 'to': dest}
     resp = s.post(self.url1, headers=self.headers1, data=data1)
     try:
         if (resp.json()['translation']):
             return resp.json()['translation'][0]
     except:
         utils.printf('使用有道备用翻译通道2')
         return self.trans2(text, dest, src)
Пример #3
0
 def translate_i18ns(self, dest, word, language):
     if (not language):
         return 'null'
     tlanguage = 'translations.' + language
     uri = "https://i18ns.com/translate/_search"
     headers = {
         "Content-Type":
         "application/json",
         "Authorization":
         "Basic aTE4bnM6KioqKioq",
         "user-agent":
         "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:63.0) Gecko/20100101 Firefox/63.0"
     }
     body = json.dumps({
         "query": {
             "simple_query_string": {
                 "query": word,
                 "fields": [tlanguage],
                 "minimum_should_match": "100%",
                 "default_operator": "AND",
                 "analyzer": "smartcn"
             }
         }
     })
     response = requests.post(url=uri,
                              data=body,
                              headers=headers,
                              timeout=120)
     if response.status_code != 200:
         return 'null'
     txd = []
     try:
         tx = json.loads(response.text, encoding="UTF-8")
         txd = tx['hits']['hits'][0]['_source']['translations']
     except Exception as e:
         return 'null'
     if (len(txd) > 1):
         isExist = False
         for x in txd:
             if (language == x['lang']):
                 orit = json.dumps(x[language], ensure_ascii=False)
                 orit = orit.replace('[', '').replace(']',
                                                      '').replace('"', '')
                 if (word == orit):
                     isExist = True
         if (isExist):
             for x in txd:
                 if (dest == x['lang']):
                     utils.printf(
                         'use \'https://i18ns.com/\' translation ' + word +
                         ' to ' + x[dest][0] +
                         ',others use google translation')
                     return x[dest][0] + ''
     return 'null'
Пример #4
0
    def translate_doc(self, filepath, destination, sourcelanguage, channel):
        channel = network.select_network(channel)
        self.log(channel, destination)

        filepath = self.get_file(filepath)
        pathArray = filepath.split(pathSeparator)

        oldFileName = pathArray[len(pathArray) - 1]
        fileType = oldFileName.split('.')[len(oldFileName.split('.')) - 1]
        currentPath = filepath.replace(
            pathSeparator +
            oldFileName, '') if len(pathArray) > 2 else os.path.abspath('.')

        newFile = ''
        if (destination == 'zh-hant' or destination == 'zh-hans'):
            newFile = os.path.join(
                currentPath, 'translate_' + destination + '_' + oldFileName)
        else:
            newFile = os.path.join(
                currentPath, 'translate_' + destination + '_by_' + channel +
                '_' + oldFileName)
        txd = ''
        utils.printf('translating..')

        # text
        if (fileType.lower() == 'text' or fileType.lower() == 'txt'):
            self.write_tx(filepath, newFile, r"text", r"text", destination,
                          sourcelanguage, channel)
        # oc:xx.string
        elif (fileType.lower() == 'strings'):
            self.write_tx(filepath, newFile, r"=\s*\"(.+?)\"\s*;",
                          '="' + 'content' + '";', destination, sourcelanguage,
                          channel)
        # java:xx.xml
        elif (fileType.lower() == 'xml'):
            self.write_tx(filepath, newFile, r">\s*(.+?)\s*</string>",
                          '>' + 'content' + '</string>', destination,
                          sourcelanguage, channel)
        else:
            if (not isWindows):
                f = open(filepath)
            else:
                f = open(filepath, encoding='UTF-8')
            line = f.readline()
            while line:
                if (len(line)):
                    txd += self.translate(line, destination, sourcelanguage,
                                          channel) + '\n'
                line = f.readline()
            f.close()
            f = open(newFile, 'w+')
            f.write(txd)
            f.close()
        utils.printf('translation completed,file saved in [' + newFile + ']')
Пример #5
0
    def translate_text(self, text, destination, sourcelanguage, channel):

        channel = network.select_network(channel)
        self.log(channel, destination)

        if (channel == 'None'):
            pass
        elif (channel == 'google'):
            utils.printf(mkGoogleTranslator().translate_text(
                text, dest=destination).text)
        else:
            utils.printf(mkYouDaoTranslator().translate(
                text, destination, sourcelanguage))
Пример #6
0
 def trans3(self, text, dest, src):
     utils.printf('使用接口,仅支持中英互译,将翻译为英文')
     params = {
         'keyfrom': 'woodcol',
         'key': '1522180019',
         'type': 'data',
         'doctype': 'json',
         'version': '1.1',
         'q': text
     }
     try:
         r = requests.get('http://fanyi.youdao.com/openapi.do',
                          params=params)
         r.raise_for_status()
         self.result = r.json()
         return self.result['translation'][0]
     except RequestException as e:
         utils.printf(
             '有道免费接口遭遇封锁,请联系作者:https://github.com/mythkiven/mkTranslate')
         sys.exit()
Пример #7
0
    def translate(self, word, destination, language, channel):
        if (len(word) == 0):
            return 'null'
        try:
            tx = self.translate_i18ns(destination, word, language)
            if (tx != 'null'):
                return tx
        except Exception as e:
            utils.printf('')
        if (destination.lower() == 'zh-hant'):
            return mkConverter('zh-hant').convert(word)
        elif (destination.lower() == 'zh-hans'):
            return mkConverter('zh-hans').convert(word)
        else:
            pass

        if (channel == 'google'):
            return mkGoogleTranslator().translate(word, dest=destination).text
        else:
            return mkYouDaoTranslator().translate(word, destination, language)
Пример #8
0
 def feed(self, char, map):
     node = map[self.pool + char]
     if node.have_child:
         if node.is_tail:
             if node.is_original:
                 cond = UNMATCHED_SWITCH
             else:
                 cond = MATCHED_SWITCH
         else:
             cond = CONNECTOR
     else:
         if node.is_tail:
             cond = TAIL
         else:
             cond = ERROR
     new = None
     if cond == ERROR:
         self.state = FAIL
     elif cond == TAIL:
         if self.state == WAIT_TAIL and node.is_original_long_word():
             self.state = FAIL
         else:
             self.final += node.to_word
             self.len += 1
             self.pool = UEMPTY
             self.state = END
     elif self.state == START or self.state == WAIT_TAIL:
         if cond == MATCHED_SWITCH:
             new = self.clone(node.from_word)
             self.final += node.to_word
             self.len += 1
             self.state = END
             self.pool = UEMPTY
         elif cond == UNMATCHED_SWITCH or cond == CONNECTOR:
             if self.state == START:
                 new = self.clone(node.from_word)
                 self.final += node.to_word
                 self.len += 1
                 self.state = END
             else:
                 if node.is_follow(self.pool):
                     self.state = FAIL
                 else:
                     self.pool = node.from_word
     elif self.state == END:
         self.state = START
         new = self.feed(char, map)
     elif self.state == FAIL:
         raise utils.printf('Translate States Machine '
                            'have error with input data %s' % node)
     return new
Пример #9
0
 def log(self, channel, dest):
     if (dest == 'zh-hant' or dest == 'zh-hans'):
         return
     if (channel == 'None'):
         utils.printf('[No network, no translation!]')
         sys.exit()
     elif (channel == 'google'):
         utils.printf('[Use google translation]')
     else:
         utils.printf('[Use youdao translation]')