Python googletrans.Translator() Examples
The following are 30
code examples of googletrans.Translator().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
googletrans
, or try the search function
.
Example #1
Source File: translate.py From 15-minute-apps with MIT License | 7 votes |
def __init__(self, *args, **kwargs): super(MainWindow, self).__init__(*args, **kwargs) self.setupUi(self) self.translator = Translator() self.destTextEdit.setReadOnly(True) if GOOGLE_TRANSLATE_AVAILABLE: self.srcLanguage.addItems(LANGUAGES.keys()) self.srcLanguage.currentTextChanged[str].connect(self.update_src_language) self.srcLanguage.setCurrentText('English') else: self.srcLanguage.hide() self.translateButton.pressed.connect(self.translate) self.show()
Example #2
Source File: translate_word_doc.py From py-googletrans with MIT License | 7 votes |
def translate_doc(filename, destination='zh-CN', mix=True): """ translate a word document type of file and save the result as document and keep the exactly same file format. :param filename: word doc file :param destination='zh-CN': :param mix=True: if True, will have original language and target language into the same doc. paragraphs by paragraphs. """ def tx(t): return Translator().translate(t, dest=destination).text doc = Document(filename) for p in doc.paragraphs: txd = tx(p.text) p.text = p.text + ('\n' + txd if mix else '') for table in doc.tables: for row in table.rows: for cell in row.cells: txd = tx(cell.text) p.text = cell.text + ('\n' + txd if mix else '') f = filename.replace('.doc', destination.lower() + '.doc') doc.save(f)
Example #3
Source File: Languages.py From UniqueBible with GNU General Public License v3.0 | 6 votes |
def translateInterface(self, language): code = self.codes[language] if code in translations: config.translationLanguage = language if hasattr(myTranslation, "translation"): open("myTranslation.py", "w", encoding="utf-8").close() return True else: print("translating interface into '{0}' ...".format(language)) translator = Translator() tempDict = {} for key, value in self.translation.items(): try: tempDict[key] = translator.translate(value, dest=code).text except: tempDict[key] = value #config.translationLanguage = language self.writeMyTranslation(tempDict, language) print("Done") return True return False
Example #4
Source File: Fetch_Data_News_US.py From StockRecommendSystem with MIT License | 6 votes |
def translation(article): translator = Translator() soup = BeautifulSoup(article, 'lxml') paragraphs = soup.findAll('p') for p in paragraphs: for content in p.contents: if content.name == None and len(content) > 0: trans = youdao_translator(content) #trans = translator.translate(content, src='en', dest='zh-CN').text #print(len(content), content.name) #print(content) #print(trans) content.replace_with(trans) return str(soup.body.next)
Example #5
Source File: main.py From PyQt5-Apps with GNU General Public License v3.0 | 6 votes |
def run(self): Data = [] global GTransData T = Translator(service_urls=["translate.google.cn"]) # ts = T.translate(['The quick brown fox', 'jumps over', 'the lazy dog'], dest='zh-CN') try: ts = T.translate(self.content, dest=self.dest) if isinstance(ts.text, list): for i in ts: Data.append(i.text) GTransData = Data else: GTransData = ts.text except: GTransData = "An error happended. Please retry..." self.trigger.emit() # emit signal once translatation is finfished
Example #6
Source File: main.py From AdultScraperX-server with GNU General Public License v3.0 | 6 votes |
def t(dirTagLine, tran): data = base64.b64decode(tran.replace(';<*', '/')).decode("utf-8") translator = Translator() if not data == '': try: logging.info("执行翻译") if dirTagLine == 'censored' or dirTagLine == 'uncensored' or dirTagLine == 'animation': data = translator.translate(data, src='ja', dest='zh-cn').text if dirTagLine == 'europe': data = translator.translate(data, src='en', dest='zh-cn').text except Exception as ex: Log('翻译出现异常 :%s' % ex) translator = None return data
Example #7
Source File: main.py From PyQt5-Apps with GNU General Public License v3.0 | 6 votes |
def __init__(self, parent=None): super(MyWindow, self).__init__(parent) self.setupUi(self) try: with open("style.qss") as f: style = f.read() # 读取样式表 self.setStyleSheet(style) except: print("open stylesheet error") self.originText.setFocus(True) # Translator self.trans = QTranslator() # destination language self.dest = "zh-CN" # ui language : 0->zh-CN, 1->en self.lan = 0 # real-time translate self.isRealTimeTrans = False self.isCopyFromTrans = False self.connectSlots()
Example #8
Source File: Languages.py From UniqueBible with GNU General Public License v3.0 | 6 votes |
def createTranslationTemplates(self): if googletransInstall: for code in self.codes.values(): print("creating '{0}' template ...".format(code)) translator = Translator() tempDict = {} for key, value in self.translation.items(): tempDict[key] = value # Note: Attempted to use Google Translate to translate interface into all languages, but access is blocked in the middle of the operation. It looks like Google blocks access by ip, when there are too many queries within a short time. # Don't use the following 4 lines, or ip will be blocked for Google Translate # try: # tempDict[key] = translator.translate(value, dest=code).text # except: # tempDict[key] = value with open("translations.py", "a", encoding="utf-8") as fileObj: code = code.replace("-", "") fileObj.write("uB{0} = {1}\n\n".format(code, pprint.pformat(tempDict)))
Example #9
Source File: google_translator.py From B.E.N.J.I. with MIT License | 6 votes |
def google_translate(link): translator = Translator() # Google Translate API pystring = " ".join(link[1:-2]) lang = detect(pystring) if link[-1] == "english": id = "en" elif link[-1] == "spanish": id = "es" elif link[-1] == "french": id = "fr" elif link[-1] == "german": id = "de" elif link[-1] == "italian": id = "it" elif link[-1] == "portugese" or link[-1] == "portuguese": id = "pt" else: id = "en" translated = translator.translate(pystring, src=lang, dest=id) # To Translate the given language to the required language print(translated.text) # Print the translated script try: speak.say("The translated text is "+translated.text) speak.runAndWait() except: print("Error speaking, here is the translated text: {}".format(translated.text))
Example #10
Source File: bot.py From telegram-moderator with MIT License | 5 votes |
def log_message(self, user_id, user_message, chat_id): if user_message is None: user_message = "[NO MESSAGE]" try: s = session() language_code = english_message = "" polarity = subjectivity = 0.0 try: # translate to English & log the original language translator = Translator() translated = translator.translate(user_message) language_code = translated.src english_message = translated.text # run basic sentiment analysis on the translated English string analysis = TextBlob(english_message) polarity = analysis.sentiment.polarity subjectivity = analysis.sentiment.subjectivity except Exception as e: print("Error translating message: {}".format(e)) msg1 = Message(user_id=user_id, message=user_message, chat_id=chat_id, language_code=language_code, english_message=english_message, polarity=polarity, subjectivity=subjectivity) s.add(msg1) s.commit() s.close() except Exception as e: print("Error logging message: {}".format(e)) print(traceback.format_exc())
Example #11
Source File: utils.py From lexico with MIT License | 5 votes |
def fetch_translations(word_to_translate): languages_to_use = ["de","es","fr","hi","ru"] translator = Translator() word_translations = [] for language in languages_to_use: word_in_this_language = translator.translate(word_to_translate, dest=language) word_with_language_info = word_in_this_language.text + " (" + language + ")" word_translations.append(word_with_language_info) return word_translations ############################################################################### ################################## EXPORT ##################################### ###############################################################################
Example #12
Source File: dictionary.py From find-all-the-new-words with MIT License | 5 votes |
def google(text): translator = Translator() return translator.translate(text,LANGUAGES["zh-cn"]).text
Example #13
Source File: nlp.py From SML-Cogs with MIT License | 5 votes |
def __init__(self, bot): self.bot = bot self.translator = Translator() self.settings = dataIO.load_json(JSON)
Example #14
Source File: translate.py From BotHub with Apache License 2.0 | 5 votes |
def _(event): if event.fwd_from: return input_str = event.pattern_match.group(1) if event.reply_to_msg_id: previous_message = await event.get_reply_message() text = previous_message.message lan = input_str or "ml" elif "|" in input_str: lan, text = input_str.split("|") else: await event.edit("`.tr LanguageCode` as reply to a message") return text = emoji.demojize(text.strip()) lan = lan.strip() translator = Translator() try: translated = translator.translate(text, dest=lan) after_tr_text = translated.text # TODO: emojify the : # either here, or before translation output_str = """**TRANSLATED** from {} to {} {}""".format( translated.src, lan, after_tr_text ) await event.edit(output_str) except Exception as exc: await event.edit(str(exc))
Example #15
Source File: translator.py From modmail-plugins with GNU General Public License v3.0 | 5 votes |
def __init__(self, bot): self.bot = bot self.db = bot.plugin_db.get_partition(self) self.translator = Translator() self.tt = set() self.enabled = True asyncio.create_task(self._set_config())
Example #16
Source File: translate.py From X-tra-Telegram with Apache License 2.0 | 5 votes |
def _(event): if event.fwd_from: return if "trim" in event.raw_text: # https://t.me/c/1220993104/192075 return input_str = event.pattern_match.group(1) if event.reply_to_msg_id: previous_message = await event.get_reply_message() text = previous_message.message lan = input_str or "ml" elif "|" in input_str: lan, text = input_str.split("|") else: await event.edit("`.tr LanguageCode` as reply to a message") return text = emoji.demojize(text.strip()) lan = lan.strip() translator = Translator() try: translated = translator.translate(text, dest=lan) after_tr_text = translated.text # TODO: emojify the : # either here, or before translation output_str = """**TRANSLATED** from {} to {} {}""".format( translated.src, lan, after_tr_text ) await event.edit(output_str) except Exception as exc: await event.edit(str(exc))
Example #17
Source File: threathuntingbook.py From pyattck with MIT License | 5 votes |
def __init__(self): super(ThreatHuntingBook, self).__init__() self.translator = Translator() self.session = requests.Session() self._dataset = [] self.__temp_attack_paths = []
Example #18
Source File: serviceTranslate.py From subtitle-translator with GNU General Public License v3.0 | 5 votes |
def __init__(self): self.translator = Translator(service_urls=[ 'translate.google.com', 'translate.google.cn', ])
Example #19
Source File: translate.py From Awesome-Python-Scripts with GNU General Public License v3.0 | 5 votes |
def Translate(text,language_text,language_to): translator = Translator() try: return translator.translate(text=text,dest=language_to,src=language_text) except: return("can't do translate please check your connection internet or language input invalid ")
Example #20
Source File: translate_test.py From googletranslate.popclipext with MIT License | 5 votes |
def showoutput(result): os.environ['result'] = result disk_prefix = commands.getoutput('osascript -e \'path to desktop as text\'').split(':')[0] icon_path = disk_prefix + os.getcwd().replace('/', ':') + ':gt.png' script = '\'display dialog "%s" with icon alias ("%s") with title "Google Translate" buttons {"Copy", "OK"} default button "OK" cancel button "Copy"\'' % (result, icon_path) os.system('osascript -e {}'.format(script)) # service_urls = ['translate.google.cn'] # translator = Translator(service_urls=service_urls) # input = 'hello' # result = translator.translate(input, dest='zh-CN').text.encode('utf-8') # showoutput(result)
Example #21
Source File: telegram_bot.py From chatbot-seminar with MIT License | 5 votes |
def send_message(chat_id, content): translator = Translator() text = translator.translate(content) url = URL + "sendMessage?chat_id={}&text={}".format(chat_id, text.text) get_url(url)
Example #22
Source File: kakao_bot.py From chatbot-seminar with MIT License | 5 votes |
def message(): data = json.loads(request.data) content = data["content"] translator = Translator() translated = translator.translate(content, dest="ko", src="en") response = { "message": { "text": translated.text } } response = json.dumps(response, ensure_ascii=False) return response
Example #23
Source File: CommonsManager.py From ProjectAlice with GNU General Public License v3.0 | 5 votes |
def translate(self, text: Union[str, list], destLang: str = None, srcLang: str = None) -> Union[str, list]: """ Translates a string or a list of strings into a different language using google translator. Especially helpful when a api is only available in one language, but the skill should support other languages aswell. :param text: string or list of strings to translate :param destLang: language to translate to (ISO639-1 code) :param srcLang: source language to translate (ISO639-1 code) :return: translated string or list of strings """ if not destLang: destLang = self.LanguageManager.activeLanguage if srcLang == destLang: return text kwargs = { 'text': text, 'dest': destLang } if srcLang: kwargs['src'] = destLang if isinstance(text, str): return Translator().translate(**kwargs).text return [result.text for result in Translator().translate(**kwargs)]
Example #24
Source File: test_client.py From py-googletrans with MIT License | 5 votes |
def test_403_error(session_mock): translator = Translator() assert translator.translate('test', dest='ko')
Example #25
Source File: test_client.py From py-googletrans with MIT License | 5 votes |
def test_timeout(): # httpx will raise ConnectError in some conditions with raises((TimeoutException, ConnectError)): translator = Translator(timeout=Timeout(0.0001)) translator.translate('안녕하세요.')
Example #26
Source File: test_client.py From py-googletrans with MIT License | 5 votes |
def test_bind_multiple_service_urls(): service_urls = [ 'translate.google.com', 'translate.google.co.kr', ] translator = Translator(service_urls=service_urls) assert translator.service_urls == service_urls assert translator.translate('test', dest='ko') assert translator.detect('Hello')
Example #27
Source File: conftest.py From py-googletrans with MIT License | 5 votes |
def translator(): from googletrans import Translator return Translator()
Example #28
Source File: translate.py From Jarvis with MIT License | 5 votes |
def performTranslation(srcs, des, tex): """ Function to actually perform the translation of text and print the result """ translator = Translator() result = translator.translate(tex, dest=des, src=srcs) result = u""" [{src}] {original} -> [{dest}] {text} [pron.] {pronunciation} """.strip().format(src=result.src, dest=result.dest, original=result.origin, text=result.text, pronunciation=result.pronunciation) print("\n" + result)
Example #29
Source File: tradutor.py From FunUtils with MIT License | 5 votes |
def traduzir(string): translator = Translator(service_urls=['translate.google.com.br',]) string = translator.translate(string, dest='pt').text return string
Example #30
Source File: main.py From tools_python with Apache License 2.0 | 5 votes |
def trans_eng(content_eng): """ 英文-中文 :param content: :return: """ translator = Translator(service_urls=['translate.google.cn']) return translator.translate(content_eng, src='en', dest='zh-cn').text