def calculate(self): if self.ent1.get() and self.ent2.get() and self.ent3.get(): first = str(self.ent1.get()) second = str(self.ent2.get()) count_system = int(self.ent3.get()) #creating the dictionary for translating self.dictionary = dictionary.Dictionary("base.csv", "r", ",") #creating the translator self.translator = translator.Translator( self.dictionary.get_dictionary(count_system), first) if self.translator.get_collection() == None: self.txt.delete(0.0, END) self.txt.insert(0.0, "Перепроверьте введенные данные!") else: self.translator = translator.Translator( self.dictionary.get_dictionary(count_system), second) if self.translator.get_collection() == None: self.txt.delete(0.0, END) self.txt.insert(0.0, "Перепроверьте введенные данные!") else: self.txt.delete(0.0, END) self.txt.insert(0.0, count(self.choose.get())) else: self.txt.delete(0.0, END) self.txt.insert(0.0, "Не все поля заполнены!")
def translateC(line): parsedLine = parsing.Parser(line) translatedComp = translator.Translator(parsedLine.comp()).comp() translatedDest = translator.Translator(parsedLine.dest()).dest() translatedJump = translator.Translator(parsedLine.jump()).jump() return '111' + translatedComp + translatedDest + translatedJump
def load_vars(): global option, autotranslator try: config = ConfigParser.ConfigParser() infile = open(inifile) config.readfp(infile) infile.close() #Parse main for item in config.items("main"): option[item[0]] = item[1] option["service"] = config.getboolean("main", "service") option["autotranslate"] = config.getboolean("main", "autotranslate") #Parse autotranslators for item in config.items("autotranslators"): source, destination = re.split(' ', item[1]) autotranslator[item[0]] = translator.Translator( source, destination) print color["dgreen"], "CancelBot TransBot transbot.ini Load Success" except EnvironmentError: print color[ "red"], "Could not open transbot.ini put it in your " + xchatdir except Exception, args: print color["red"], args
def main(self): """総理大臣のCSVファイルをHTMLページへと変換するメインプログラム。""" # ホームディレクトリの直下のデスクトップのディレクトリに、 # SouriDaijinというディレクトリを作成する。 # すでに存在すれば、当該ディレクトリを消して、新たに作り、 # 存在しなければ、当該ディレクトリを作成する。 home_directory = os.environ['HOME'] base_directory = home_directory + '/Desktop/PrimeMinisters/' if os.path.isdir(base_directory): shutil.rmtree(base_directory) os.makedirs(base_directory) # ダウンローダに必要なファイル群をすべてダウンロードしてもらい、 # 入力となるテーブルを獲得する。 a_downloader = downloader.Downloader(base_directory) a_table = a_downloader.download_all() print a_table # トランスレータに入力となるテーブルを渡して変換してもらい、 # 出力となるテーブルを獲得する。 a_translator = translator.Translator(a_table) a_table = a_translator.table() print a_table # ライタに出力となるテーブルを渡して、 # Webページを作成してもらう。 a_writer = writer.Writer(base_directory, a_table) a_writer.write() return 0
def translate(self): _ = [] trans = translator.Translator() for page in self.pages: _.append(trans.translate(page)) self.translatedPages = _ return self.translatedPages
def autoTranslate(self): _ = [] trans = translator.Translator() for page in self.pages: if not re.findall(r'[\u4e00-\u9fff]+', page): _.append(trans.translate(page)) self.translatedPages = _ return self.translatedPages
def translateLine(self, forTrans, tEn, oEn): coder = codec.Codec() tran = translator.Translator(self.opArg) decodedStr = coder.decodeString(forTrans, tEn) translated = tran.translateString(decodedStr) codedStr = coder.codeTranslated(translated, oEn) return codedStr
def main(): if len(sys.argv) == 1: print("Usage: python3 %s input_file1 input_file2 ..." % sys.argv[0]) file_list = sys.argv[1:] t = translator.Translator() for it in file_list: t.append(it) t.translate(sys.stdout)
def translate(source, dest, text, destination): try: a = translator.Translator(source, dest) response = a.translate(text) destination.command("say " + response) except KeyError, args: destination.command("say " + color["red"] + str(args) + color["close"] + " is not a valid language. Try !translators")
def __init__(self, root): super().__init__(root) self.entry_list = [] self.combobox_dict = {} self.label_dict = {} self.row_number = 0 self.translator = translator.Translator() self.skills_info = skills_info.SkillsInfo() self.helper = comboboxes_entries_helper.ComboboxesEntriesHelper() self.random_calculator = random_calculator.RandomCalculator() self.random_skills_points = random_skills_points.RandomSkillsPoints() self.create_content()
def __init__(self, filename): self.translator = translator.Translator(filename) self.inputs = { "0": 0, "1": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9, "a": 10, "b": 11, "c": 12, "d": 13, "e": 14, "f": 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, "?": 41, "~": 42, "n": 43, "'": 44, "|": 45, } self.execute()
def GenerateData(argv): savedStdout = sys.stdout file = open('.datagon.log', 'w') sys.stdout = file print('------ Starting Generating Data. ------') f = open(os.path.join(os.getcwd(), argv[0]), 'r') tokens = tokenizer.Tokenizer(f.read()) ast = parser.Parser(tokens) result = translator.Translator(ast) sys.stdout = savedStdout if len(argv) > 1: with open(argv[1], 'w') as file: file.write(result) else: print(result)
def autotranslate(word, word_eol, userdata): global autotranslator, option if word[1].lower() == 'del': if autotranslator.has_key(word[2].lower()): autotranslator.pop(word[2].lower()) print color["red"], "Autotranslator for", word[2], "deleted!" save_vars() else: print color["red"], "No Autotranslator for", word[2], "found" elif word[1].lower() == 'list': if len(autotranslator) == 0: print color["red"], "You have no auto translators!" else: print color["dgreen"], "Your auto translators are:" for key in autotranslator: print color["blue"], key, autotranslator[ key].source, autotranslator[key].destination elif word[1].lower() == 'on': option["autotranslate"] = True print color["dgreen"], "Autotranslate has been turned ON" save_vars() elif word[1].lower() == 'off': option["autotranslate"] = False print color["red"], "Autotranslate has been turned OFF" save_vars() elif word[1].lower() == 'translators': print "Available methods are:", color["blue"], str( translator.get_pairs()) else: try: autotranslator[word[1].lower()] = translator.Translator( word[2], word[3]) print color["dgreen"], "We will now auto translate", word[ 1], "from", word[2], "to", word[3] save_vars() except Exception, args: print color["red"], "Proper format is Nick FromLanguage ToLanguage" return
def main(self): """総理大臣のCSVファイルをHTMLページへと変換するメインプログラム。""" # ホームディレクトリの直下のデスクトップのディレクトリに、 # PrimeMinistersというディレクトリを作成する。 # すでに存在すれば、当該ディレクトリを消して、新たに作り、 # 存在しなければ、当該ディレクトリを作成する。 #ここからデバックのためのコメントアウト多数につき注意 #print "[example]ホームディレクトリを指定:", home_directory = os.environ['HOME'] #print home_directory print "[example]ベースディレクトリを指定:", base_directory = home_directory + '/Desktop/PrimeMinisters/' print base_directory if os.path.isdir(base_directory): print "[example]ベースディレクトリからディレクトリを削除" shutil.rmtree(base_directory) print "[example]ベースディレクトリからディレクトリを作成" os.makedirs(base_directory) # ダウンローダに必要なファイル群をすべてダウンロードしてもらい、 # 入力となるテーブルを獲得する。 a_downloader = downloader.Downloader(base_directory) a_table = a_downloader.download_all() print a_table # トランスレータに入力となるテーブルを渡して変換してもらい、 # 出力となるテーブルを獲得する。 a_translator = translator.Translator(a_table) a_table = a_translator.table() print a_table # ライタに出力となるテーブルを渡して、 # Webページを作成してもらう。 a_writer = writer.Writer(base_directory, a_table) a_writer.write() return 0
def translate(self): trans = translator.Translator() _newdata = [] for i in range(len(self.data)): _ = [] for j in range(len(self.data[i])): __ = [] if isinstance(self.data[i][j], tuple) or isinstance( self.data[i][j], list): for k in range(len(self.data[i][j])): if containChinese(self.data[i][j][k]): __.append(trans.translate(self.data[i][j][k])) else: __.append(self.data[i][j][k]) if __: _.append(__) else: if containChinese(self.data[i][j]): _.append(trans.translate(self.data[i][j])) _newdata.append(_) self.data = _newdata print(self.data)
def __init__(self, seed_tuple, timeout, translator_engine): super(BabelegramHandler, self).__init__(seed_tuple, timeout, flavors=['inline_query', 'chosen_inline_result']) logging.info('Started handler...') # Init instance variables # Create the Answerer, give it the compute function. self._answerer = telepot. async .helper.Answerer(self.bot) rank, ocur = helpers.start_rank() self.settings = { 'rank': rank, 'ocurrences': ocur, 'total_ocurrences': len(rank), 'last_ocurrences': [], 'page_size': 2 } self.cached_results = asyncio.Queue( maxsize=self.settings['page_size'] * 2) self._translator = translator.Translator(self.settings['rank'], self.cached_results, translator_engine)
def main(): # Ensure single command line argument provided if (len(sys.argv) != 2): print("Usage: assembler.py <file.asm>") exit(1) # Retrieve input file details inputFile = sys.argv[1] inputFileName = inputFile.split('.')[0] inputExtension = inputFile.split('.')[1] # Ensure .asm file provided if not (inputExtension == 'asm'): print("Usage: assembler.py <file.asm>") exit(1) # Open output file outputExtension = ".hack" outputFile = inputFileName + outputExtension output = open(outputFile, 'w') # Parse input file commands = parser.getCommands(inputFile) # Convert symbols symbolConverter = symbolHandler.SymbolHandler(commands) convertedCommands = symbolConverter.getConvertedCommands() # Translate commands codeTranslator = translator.Translator(convertedCommands) commandsTranslated = codeTranslator.getTranslatations() # Write to ourput file for command in commandsTranslated: output.write(command + '\n') output.close()
def create_content(self): self.frame = Label(self.root) self.frame.place(relx=0.5, rely=0.4, anchor=CENTER) frame_1 = Label(self.frame) frame_2 = Label(self.frame) frame_3 = Label(self.frame) frame_4 = Label(self.frame) frame_1.grid(row=0, column=0) frame_2.grid(row=1, column=0) frame_3.grid(row=2, column=0) frame_4.grid(row=3, column=0) #frame_1 label_title = Label(frame_1, text="Umiejętności zawodowe", font=("Helvetica", 16)).grid(row=0, column=0) #frame_2 label_occupation_skill_points = Label(frame_2, text="Dostępne punkty zawodowe: ").grid(row=0, column=0) occupation_skill_points = StringVar() self.entry_available_occupation_skill_points = Entry(frame_2, textvariable=occupation_skill_points, width=5) self.entry_available_occupation_skill_points.grid(row=0, column=1) self.entry_available_occupation_skill_points.insert(0, Data.data["occupation_skill_points"]) #frame_3 self.translator = translator.Translator() self.create_skills_labels_and_entries(frame_3) #frame_4 self.btn_next_window = Button(frame_4, text="Dalej", width=10, command=self.next_window, state=DISABLED) self.btn_next_window.grid(row=0, column=1, pady=20, padx=50, stick=E) btn_previous_window = Button(frame_4, text="Cofnij", width=10, command=self.previous_window).grid(row=0, column=0, pady=20, padx=50, stick=W) self.btn_random = Button(frame_4, text="Random", width=20, command=self.random_button_click) self.btn_random.grid(row=1, column=0, columnspan=2, pady=5) btn_reset = Button(frame_4, text="Reset", width=20, command=self.reset_skills_points).grid(row=2, column=0, columnspan=2, pady=5) occupation_skill_points.trace("w", lambda _, __, ___, sv=occupation_skill_points: self.helper.check_base_skill_points(self.entry_available_occupation_skill_points, occupation_skill_points.get(), self.entry_list, self.btn_next_window)) self.entry_available_occupation_skill_points.config(state="disabled")
cmd = "Storage element table not found: %s" % seFile raise RuntimeError, cmd crabFile = os.environ['MIT_PROD_DIR'] + '/' + mitCfg + '/' + version + '/' + 'crab.cfg' if not os.path.exists(crabFile): cmd = "Crab file not found: %s" % crabFile raise RuntimeError, cmd cmsswFile = os.environ['MIT_PROD_DIR'] + '/' + mitCfg + '/' + version + '/' + cmssw + '.py' if not os.path.exists(cmsswFile): cmd = "Cmssw file not found: %s" % cmsswFile cmd = " XXXX ERROR no valid configuration found XXXX" raise RuntimeError, cmd cmsswPy = cmssw + '_' + crabId + '.py' # Prepare the ce/se translator trans = translator.Translator(os.environ['MIT_PROD_DIR']+'/'+mitCfg+'/'+version+'/ceTable', os.environ['MIT_PROD_DIR']+'/'+mitCfg+'/'+version+'/seTable', os.environ['MIT_PROD_DIR']+'/'+mitCfg+'/'+version+'/preferredSites') # Create the corresponding crab task crabTask = task.Task(crabId,cmsDataset,mitDataset,mitCfg,version,cmssw) if crabTask.mitDataset == 'undefined' or crabTask.cmsDataset == 'undefined': print " ERROR - dataset not defined." sys.exit(1) else: mitDataset = crabTask.mitDataset cmsDataset = crabTask.cmsDataset #dbs = crabTask.dbs # Deal with obvious problems if cmsDataset == None or mitDataset == None: cmd = "--cmsDataset & --mitDataset " + \
def Main(doImp, scriptsLoc): global debug, __version__, doImport, scriptsLocation, defaultFilename, valsLoaded if _ERROR or _PERROR: return valsLoaded = False doImport = doImp if scriptsLoc == "": scriptsLoc = Blender.Get('scriptsdir') if not scriptsLoc: scriptsLoc = Blender.Get('uscriptsdir') if scriptsLoc: scriptsLocation = scriptsLoc + Blender.sys.sep + 'bpymodules' + Blender.sys.sep + 'colladaImEx' + Blender.sys.sep else: print 'Could not find a scripts path' else: scriptsLocation = scriptsLoc if not ReloadModules(): print 'cannot reload all modules' return False # Clear the console cutils.ClearConsole() # set the debuglevel if debug: cutils.Debug.SetLevel('DEBUG') else: cutils.Debug.SetLevel('FEEDBACK') cutils.Debug.Debug( 'Illusoft Collada 1.4 Plugin v%s started' % (__version__), 'FEEDBACK') # Create a Collada <-> Blender Translator if debug: print 'keep track of the time to execute this script' #--------- startTime = Blender.sys.time() ##fileurl = scriptsDir fileurl = '' if doImport: fileurl += defaultFileUrl else: fileurl += defaultExportUrl if debprn: print 'deb: fileurl=', fileurl #------- useTriangles = False usePolygons = False bakeMatrices = False exportSelection = False newScene = True clearScene = False lookAt = False usePhysics = True exportCurrentScene = False exportRelativePaths = False useUV = False sampleAnimation = False onlyMainScene = False checkUnweightedVerts = False unit_name = "centimeter" unit_length_in_meter = "0.01" transl = translator.Translator( doImport, __version__, debug, fileurl, useTriangles, usePolygons, bakeMatrices, exportSelection, newScene, clearScene, lookAt, usePhysics, exportCurrentScene, exportRelativePaths, useUV, sampleAnimation, onlyMainScene, checkUnweightedVerts, unit_name, unit_length_in_meter) ##transl = translator.Translator(doImport,__version__,debug,fileurl) ##translator = Translator(False,__version__,debug,scriptsDir+defaultExportUrl) ##translator = Translator(True,__version__,debug,scriptsDir+defaultExportUrl) # Redraw al 3D windows. if debprn: print 'deb: ---- the end ----' #----- Blender.Window.RedrawAll() # calculate the elapsed time endTime = Blender.sys.time() elapsedTime = endTime - startTime cutils.Debug.Debug('FINISHED - time elapsed: %.1f' % (elapsedTime), 'FEEDBACK') # Hide the wait cursor in blender Blender.Window.WaitCursor(0) else: defFilename = Blender.sys.dirname( Blender.sys.progname) + Blender.sys.sep colladaReg = Blender.Registry.GetKey('collada', True) if not (colladaReg is None) and 'path' in colladaReg and Blender.sys.exists( colladaReg['path']): defFilename = colladaReg['path'] elif not (doImport): defFilename += 'untitled.dae' defaultFilename = defFilename Blender.Draw.Register(Gui, Event, ButtonEvent) # registering the 3 callbacks
def ButtonEvent(evt): global toggleLookAt, toggleBakeMatrix, toggleExportSelection,toggleNewScene, \ toggleClearScene, toggleTriangles, togglePolygons, doImport, defaultFilename, \ fileSelectorShown, fileButton, valsLoaded, togglePhysics, \ toggleExportCurrentScene, toggleExportRelativePaths, toggleUseUV, \ toggleSampleAnimation, toggleCheckUnweightedVerts, toggleOnlyMainScene, \ valueUnitLengthInMeter checkImportButtons = False if evt == 1: toggle = 1 - toggle Blender.Draw.Redraw(1) elif evt == 2: # browse file browseText = '' if doImport: browseText = 'Import .dae' else: browseText = 'Export .dae' Blender.Window.FileSelector(FileSelected, browseText, defaultFilename) Blender.Draw.Redraw(1) elif evt == 3: Blender.Draw.Exit() elif evt == 4 or evt == 12: # Ok, time to export/import #keep track of the time to execute this script startTime = Blender.sys.time() fileName = fileButton.val dirName = Blender.sys.dirname(fileName) + Blender.sys.sep exists = Blender.sys.exists(fileName) if exists == 1 and not doImport: overwrite = Blender.Draw.PupMenu( "File Already Exists, Overwrite?%t|Yes%x1|No%x0") if not overwrite == 1: return False elif exists != 1 and doImport: Blender.Draw.PupMenu("File does not exist: %t|" + fileName) cutils.Debug.Debug('File(%s) does not exist' % (fileName), 'ERROR') return False elif not Blender.sys.exists(dirName): Blender.Draw.PupMenu("Path is not valid: %t|" + dirName) cutils.Debug.Debug('Path is not valid: %s' % (dirName), 'ERROR') return False if toggleTriangles is None: useTriangles = False else: useTriangles = bool(toggleTriangles.val) if togglePolygons is None: usePolygons = False else: usePolygons = bool(togglePolygons.val) if toggleBakeMatrix is None: bakeMatrices = False else: bakeMatrices = bool(toggleBakeMatrix.val) if toggleExportSelection is None: exportSelection = False else: exportSelection = bool(toggleExportSelection.val) if toggleNewScene is None: newScene = False else: newScene = bool(toggleNewScene.val) if toggleClearScene is None: clearScene = False else: clearScene = bool(toggleClearScene.val) if toggleOnlyMainScene is None: onlyMainScene = False else: onlyMainScene = bool(toggleOnlyMainScene.val) if toggleLookAt is None: lookAt = False else: lookAt = bool(toggleLookAt.val) if togglePhysics is None: usePhysics = True else: usePhysics = not bool(togglePhysics.val) if toggleExportCurrentScene is None: exportCurrentScene = False else: exportCurrentScene = bool(toggleExportCurrentScene.val) if toggleExportRelativePaths is None: exportRelativePaths = False else: exportRelativePaths = bool(toggleExportRelativePaths.val) if toggleUseUV is None: useUV = False else: useUV = bool(toggleUseUV.val) if toggleSampleAnimation is None: sampleAnimation = False else: sampleAnimation = bool(toggleSampleAnimation.val) if toggleCheckUnweightedVerts is None: checkUnweightedVerts = False else: checkUnweightedVerts = bool(toggleCheckUnweightedVerts.val) if toggleApplyModifiers is None: applyModifiers = False else: applyModifiers = bool(toggleApplyModifiers.val) #if valueUnitName is None: # unitName = "centimeter" #else: # unitName = valueUnitName.val if valueUnitLengthInMeter is None: unitLengthInMeter = "0.01" else: unitLengthInMeter = convertToFloat(valueUnitLengthInMeter.val, 0.01) unitName = getUnitName(unitLengthInMeter) d = Blender.Registry.GetKey('collada', True) if d is None: d = dict() d['path'] = fileName if doImport: d['newScene'] = newScene d['clearScene'] = clearScene d['onlyMainScene'] = onlyMainScene else: d['useTriangles'] = useTriangles d['usePolygons'] = usePolygons d['bakeMatrices'] = bakeMatrices d['exportSelection'] = exportSelection d['lookAt'] = lookAt d['usePhysics'] = usePhysics d['exportCurrentScene'] = exportCurrentScene d['exportRelativePaths'] = exportRelativePaths d['useUV'] = useUV d['sampleAnimation'] = sampleAnimation d['applyModifiers'] = applyModifiers d['checkUnweightedVerts'] = checkUnweightedVerts d['unitName'] = unitName d['unitLengthInMeter'] = unitLengthInMeter Blender.Registry.SetKey('collada', d, True) if doImport: importExportText = "Import" else: importExportText = "Export" try: transl = translator.Translator(doImport,__version__,debug,fileName, \ useTriangles, usePolygons, bakeMatrices,\ exportSelection, newScene, clearScene, \ lookAt, usePhysics, exportCurrentScene, \ exportRelativePaths, useUV, sampleAnimation, \ onlyMainScene, applyModifiers, checkUnweightedVerts, \ unitName, unitLengthInMeter) cutils.Debug.Debug('Time to process and save data: %.1f' \ % CalcElapsedTime(startTime), 'FEEDBACK') # Redraw all 3D windows. Blender.Window.RedrawAll() Blender.Draw.PupMenu(importExportText + " Successful %t") except: Blender.Draw.PupMenu( importExportText + "ing failed%t | Check the console for more info") raise # throw the exception cutils.Debug.Debug('FINISHED - time elapsed: %.1f' % CalcElapsedTime(startTime), \ 'FEEDBACK') # Hide the wait cursor in blender Blender.Window.WaitCursor(0) if evt == 4: Blender.Draw.Exit() valsLoaded = False elif evt == 6: # Toggle Triangles if toggleTriangles.val: togglePolygons.val = 0 Blender.Draw.Redraw(1) elif evt == 7: # Toggle Polygons if togglePolygons.val: toggleTriangles.val = 0 Blender.Draw.Redraw(1) elif evt == 9: # Toggle Create new Scene if toggleNewScene.val: toggleClearScene.val = 0 checkImportButtons = True elif evt == 10: # Toggle Clear current Scene if toggleClearScene.val: toggleNewScene.val = 0 checkImportButtons = True elif evt == 17: # Toggle Only Main Scene checkImportButtons = True elif evt == 18: # Check data input for unit length if valueUnitLengthInMeter != None: nval = convertToFloat(valueUnitLengthInMeter.val, 0.01) if nval != valueUnitLengthInMeter.val: valueUnitLengthInMeter.val = nval Blender.Draw.Redraw(1) if checkImportButtons: if not toggleOnlyMainScene.val: if not toggleClearScene.val and not toggleNewScene.val: toggleNewScene.val = True Blender.Draw.Redraw(1)
def __init__(self, root): super().__init__(root) self.translator = translator.Translator() self.random_calculator = random_calculator.RandomCalculator() self.credit_rating_calculator = credit_rating_calculator.CreditRatingCalculator() self.creat_content()
class tagSENT: #instance of the translator class trans = translator.Translator() #instance of the sentiment class senti = sentiment.Sentiment() #instance of the part of speech tagger classs tagger = POS_tagger.POS_tagger() #variable that holds the variable for intensifiers [words that increase the polarity of a word] intensifiers = open("trainingData/intensifiers.txt","r").read().split("\n") #negators are words that flip the polarity of a word negators = ["hindi","wala","walang","di","Hindi","Wala","Walang","Di"] #attenuators are words that decrease the polarity of a word attenuators = ["medyo"] def __init__(self): #train both models self.trans.train() self.senti.train() pass """ this method is used to predict each of the sentiment of *sentiment bearing* words such words are usually a non prepositional or non article words (n., adj., adv...) - accepts a string as a parameter, returns a list in a format [ [<word1>,[positive,negative]] , [...] , ...] """ def predict_each(self,text): #tag the words first using the pos tagger #the format of the tagged words are based from the output of the tagging prediction #[ [<word>,tag] , [<word2>,tag2] , ... ] tagged_words = self.tagger.predict(text) #this variable stores the total score of the prediction score = [0,0] #this variable stores the prediction, uh yeah obviously. prediction = [] #loop through all the tagged words for word_tag in tagged_words: #store the sentiment score of the word being analyzed senti_score = [0,0] #check if the pos tag of the word is a possible sentiment bearing word #sentiment bearing words are words with a pos tag that is not prep., conj. or vbl. if word_tag[1] in ["n","v","adv","adj","AMB","UNK"]: #translate the tagalog word to english. This variable is a list of translations : [trans1, trans2, trans3] translated = self.trans.translate(word_tag[0]) #use the prediction module of sentiment class by feeding all the translations. This variable stores: [positive, negative] senti_score = self.senti.predict_multi(translated) #append to the word container its translation word_tag.append(translated) #if the the polarity of both is equal, most likely the word returned a [0,0] because it wasn't translated if senti_score[0] == senti_score[1]: #check if the word contains an amplifier prefix if word_tag[0].startswith("napaka") or word_tag[0].startswith("pinaka"): #replace the infix napaka/ pinaka with ma, and then predict its sentiment score senti_score = self.senti.predict_multi(self.trans.translate(re.sub("napaka|pinaka","ma",word_tag[0]))) #increase the polarity of the word by checking whether it has a amplifying prefix #or it is a repeating word ex: poging-pogi, matabang-mataba #this intensification seeks for "-" in the word senti_score = self.word_intensify(word_tag[0],senti_score) #add the extracted sentiment score to the total sentiment score, [0] is postive, [1] is negative score[0] += senti_score[0] score[1] += senti_score[1] #clear the score of the polarity that is lesser #if the positive is greater than the negative if senti_score[0]>senti_score[1]: #clear the negative score senti_score = [senti_score[0],0] #if the negative is greater than the positive elif senti_score[0]<senti_score[1]: #clear the positive score senti_score = [0,senti_score[1]] #add the current prediction of the word to the list of predicted words (prediction) variable prediction.append([word_tag,senti_score]) #use the nearby_intensify to check and apply the words that intensify its nearby word (forward) #ex: sobrang galing, this amplifies galing. the search for the target word to be amplified is forward prediction = self.nearby_intensify(prediction) #same as the previous method, but the search is in reverse #ex: ang galing niya sobra. prediction = self.nearby_intensify_reverse(prediction) #check for flipping words (negators), the search is only forward prediction = self.negation(prediction) #return the list containing the predictions return prediction """ method that intensifies the word depending on its affixes parameters: word: string, the word being analyzed score: original polarity scores """ def word_intensify(self,word,score): #if the word startswith napaka/ pinaka if word.startswith("napaka") or word.startswith("pinaka"): #if the positive score is greater than the negative, amplify it 70% if score[0] > score[1]: score[0] *= 1.7 #vice versa else: score[1] *= 1.7 #if the word contains a "-" amplify the polarity by 50% if word.find("-") >=0: if score[0] > score[1]: score[0] *= 1.5 else: score[1] *= 1.5 #return the modified score return score """ this method checks whether there is an amplfying pattern within the prediction ex: ADV. PREP. N. ADJ. this method amplifies the ADJ, as given from this example parameter - prediction: this can be extracted from predict_each """ def nearby_intensify(self,prediction): #loop all over the prediction list for index in range(len(prediction)): #do this if the following condition/s is/are satisfied #if the word being predicted is an attenuator #if the word being predicted is an intensifier #if the prediction score of the word is not neutral (0,0) and the #pos tag of the word is either an adj/ adv, and the word is not a negator if prediction[index][0][0] in self.attenuators or prediction[index][0][0] in self.intensifiers or (prediction[index][1] != [0,0] and prediction[index][0][1] in ["adv","adj"] and prediction[index][0][0] not in self.negators ): #trigger variable, this changes to true if the word being intensified is already found trig = False #searches ahead of the words for word_score in prediction[index+1:]: #if the pos tag of the word is anything but adverb if word_score[0][1] in ["adj","AMB","n","v","UNK"]: #if the word is an intensifier if prediction[index][0][0] in self.intensifiers: #amplify thes greater polarity score by 70% if word_score[1][0] > word_score[1][1]: word_score[1][0] *= 1.7 else: word_score[1][1] *= 1.7 #trigger the trig variable trig = True #if the word is an attenuator if prediction[index][0][0] in self.attenuators: #weaken the polarity by 45% word_score[1] = [word_score[1][0]*0.65,word_score[1][1]*0.65] trig = True #else if the pos tag of the word is an adjective elif prediction[index][0][1] == "adj": #if the word is not a negator/attenuator/intensifier if word_score[0][0] not in self.negators and word_score[0][0] not in self.attenuators and word_score[0][0] not in self.intensifiers: #add the polarity of the describing word to the target word word_score[1] = [word_score[1][0] + prediction[index][1][0] , word_score[1][1] + prediction[index][1][1]] #clear the lesser scored polarity if word_score[1][0]>word_score[1][1]: word_score[1][1] = 0 elif word_score[1][0]<word_score[1][1]: word_score[1][0] = 0 #trigger trig = True #if it hasn't passed the previous conditions else : #if the polarity score isn't neutral if word_score[1] != [0,0]: #multiply the greater polarity of the target word that by the polarity of the describing word if prediction[index][1][0] >prediction[index][1][1]: word_score[1][0] *= (1+prediction[index][1][0]) else: word_score[1][1] *= (1+prediction[index][1][1]) #trigger trig = True #if triggered, turn the polarity score of the describing word to neutral [0,0] if trig: prediction[index][1] = [0,0] #stop the loop break #stop the loop if the pos tag of the target word is a stopper elif word_score[0][1] in ["stopper","conj"]: break #return the modified prediction return prediction """ this method is just like the nearby_intensify however, we reverse the prediction list so it looks backwards and not forward """ def nearby_intensify_reverse(self,prediction): #reverse the prediction list in place prediction.reverse() #loop (forward) through all the elements of reversed prediction; essentially it looks backwards now for index in range(len(prediction)): #if the word is an intensifier then if prediction[index][0][0] in self.intensifiers : #look forward for the target word for word_score in prediction[index+1:]: #if the word is not an adverb then if word_score[0][1] in ["adj","AMB","n","v","UNK"]: #amplify the polarity of the target word by 70% if word_score[1][0] > word_score[1][1]: word_score[1][0] *= 1.7 else: word_score[1][1] *= 1.7 #turn the describing word to neutral prediction[index][1] = [0,0] #stop the loop break #bring the prediction list into its original position by re-reversing it prediction.reverse() #return the modified prediction return prediction """ this method utilizes the negators to achieve the flipping ability parameter - prediction: can be extracted from predict_each """ def negation(self,prediction): #loop through the prediction list, checking if there is a negator on the list for index in range(len(prediction)): #if a negator is seen then if prediction[index][0][0] in self.negators: #loop forwards the list for word_score in prediction[index+1:]: #if the word is "mas", stop the loop if word_score[0][0] in ["mas"]: break #if the word is an adjective/noun/verb and it is not neutral if word_score[0][1] in ["adj","v","n"] and (word_score[1] != [0.0,0.0] or word_score[1] != [0,0]): #reverse the polarity word_score[1] = word_score[1][::-1] #turn the negator into a neutral polarity prediction[index][1] = [0,0] #stop the loop break #return the modified prediction return prediction """ this is the method that predicts the given text and outputs the total parameters - text: string, a grammatically correct text output - total - (<prediction_label>,[positive,negative],prediction_list) """ def predict(self,text): #seperate all punctuations to be a space from its neighbors #example: Siya ay mabilis, ngunit mali-mali ang kanyang gawa. -> Siya ay mabilis , ngunit mali-mali ang kanyang gawa . text = re.sub("([A-Za-z0-9])([.;,!?])","\g<1> \g<2>",text) #use the predict_each method to get the prediction_list pred = self.predict_each(text) #return the analyzed total of the prediction list return self.total(pred) """ this is the method that analyzes the output of predict_each (the prediction list) parameters - prediction - a list containing the details of the prediction; can be get from predict_each method output - total - (<prediction_label>,[positive,negative],prediction_list) """ def total(self,prediction): #this the variable that stores the total sentiment of the given text total_sentiment = [0,0] #loop through all the predictions for i in prediction: #if the positive polarity is greater than 0.039 add it to the positive total #0.039 is the threshold for a relevant polarity if i[1][0] > 0.039: total_sentiment[0]+= i[1][0] #same for negative if i[1][1] > 0.039: total_sentiment[1]+= i[1][1] #this variable holds the difference diff = 0 #check if there is no zero value in the polarity score if 0 not in total_sentiment: #get the total of the sentiments (would be used for percentage) total = total_sentiment[0] + total_sentiment[1] #then, get the percentage of each polarity perc_neg = total/total_sentiment[1] perc_pos = total/total_sentiment[0] #get the difference between the percentages of the polarities diff = abs(perc_neg - perc_pos) #if the difference between the polarities is greater than .10, then if total_sentiment>0.05 and diff>=.10: #increase the negative by 50% #studies show that people are biased to say positive than negative words #thus positive scores tend to get higher than negatives #therefore we amplify the bias to show true polarity total_sentiment[1] = total_sentiment[1] * 1.5 #return the corresponding greater polarity if total_sentiment[0] > total_sentiment[1]: return ("POSITIVE",total_sentiment,prediction) elif total_sentiment[0] < total_sentiment[1]: return ("NEGATIVE",total_sentiment,prediction) else: return ("NEUTRAL",total_sentiment,prediction)
def create_skills_labels_and_entries(self, frame): self.translator = translator.Translator() self.label_dict = {} self.combobox_dict = {} skills_list = self.skill_formater.get_occupation_skills_pl() skills_list.append("Majętność") for index, skill in enumerate(skills_list): if "lub" in skill: or_skills = skill.split(" lub ") for or_skill in or_skills.copy(): or_skill_enum = self.translator.get_skill_for_translation(or_skill) or_skill_enum_string = or_skill_enum.name.title() if or_skill_enum_string == "Other_Language": or_skill_enum_string = "Other Language" if or_skill_enum_string.strip() in skills_info.SkillsInfo.enums_dict.keys(): or_skills.remove(or_skill) enum = skills_info.SkillsInfo.enums_dict[or_skill_enum_string.strip()] enum_list = [member[1] for member in enum.__members__.items()] for e in enum_list: or_skills.append(self.translator.get_translation_for_skill(e)) or_skills.sort() entry = self.create_entry(frame, index, or_skills[0]) self.entry_list.append(entry) self.create_combobox(frame, index, or_skills) elif "Dowolna umiejętność" in skill: all_skills_enums_list = skills_info.SkillsInfo.get_all_skills_list() all_skills_names_pl = [self.translator.get_translation_for_skill(skill) for skill in all_skills_enums_list] all_skills_names_pl.sort() entry = self.create_entry(frame, index, all_skills_names_pl[0]) self.entry_list.append(entry) self.create_combobox(frame, index, all_skills_names_pl) elif skill == "Sztuka/Rzemiosło": self.create_combobox_pair_for_enum(ArtCraft, index, frame) elif skill == "Język Obcy": self.create_combobox_pair_for_enum(Language, index, frame) elif skill == "Walka Wręcz": self.create_combobox_pair_for_enum(Fighting, index, frame) elif skill == "Broń Palna": self.create_combobox_pair_for_enum(Firearm, index, frame) elif skill == "Nauka": self.create_combobox_pair_for_enum(Science, index, frame) elif skill == "Pilotowanie": self.create_combobox_pair_for_enum(Pilot, index, frame) elif skill == "Sztuka Przetrwania": self.create_combobox_pair_for_enum(Survival, index, frame) else: entry = self.create_entry(frame, index, skill) self.entry_list.append(entry) label_skill = Label(frame, text=skill) label_skill.grid(row=index, column=0) self.label_dict[index] = label_skill self.remove_labels_skills_from_comboboxes()
def translate(self, text, or_lang='ru', tar_lang='en'): return translator.Translator().translate(text, or_lang, tar_lang)
# TileCutter User Interface Module # Season Images Control import logging import wx, imres import translator gt = translator.Translator() class ControlSeason(wx.Panel): """Box containing season image controls""" season_names = ["summer", "snow", "autumn", "winter", "spring"] season_title = ["Summer", "Snow", "Autumn", "Winter", "Spring"] def __init__(self, parent, app): logging.info("Create season controls") wx.Panel.__init__(self, parent=parent, id=wx.ID_ANY) self.app = app # Setup sizers self.sizer = wx.BoxSizer(wx.VERTICAL) self.s_seasons_flex = wx.FlexGridSizer(0, 5, 0, 0) self.s_seasons_flex.AddGrowableCol(4) # Header text self.label = wx.StaticText(self, wx.ID_ANY, "", (-1, -1), (-1, -1), wx.ALIGN_LEFT) # Add items self.seasons_images = []
def __init__(self): Cmd.__init__(self) self.ex = Executor() self.trans = translator.Translator()
import converter import translator import memory import errors import executor Reporter = errors.ErrorReporter('__main.py__') Converter = converter.Converter('example.cpp', 'example.intpr') Converter.start_convertation() Translator = translator.Translator('example.intpr') OP_LIST = Translator.translate() Executor = executor.Executor() Executor.execute(OP_LIST) print(Executor.dump_mem())
def setUpClass(cls): # For Speed cls.ex = executor.Executor() cls.trans = translator.Translator()
def do_reload(self, line): reload(translator) self.trans = translator.Translator() return False