def loadfiles(): Dictionary.loadDictionary('dictionary') global suffixes, modals, person, imperitive file = FileHandler.loadFile("Resources/person.csv", "r") for line in file: line = line.strip() p = line.split(',') print(len(p)) person.update({p[0]: [p[1], p[2], p[3], p[4], p[5], p[6], p[7]]}) file.close() file = FileHandler.loadFile("Resources/modals.csv", "r") for line in file: line = line.strip() p = line.split(',') modals.update({p[0]: [p[1]]}) file.close() file = FileHandler.loadFile("Resources/suffixes.csv", "r") for line in file: line = line.strip() p = line.split(',') # print(str(p)) suffixes.update({p[0]: [p[1]]}) file.close() file = FileHandler.loadFile("Resources/imperative.csv", "r") for line in file: line = line.strip() p = line.split(',') imperitive.update({p[0]: [ p[1], p[2], p[3], p[4]]})
def print_menu(): print("MENU:\n") print("(P)ronunciation - Using IPA \n") print("(D)ictionary - English/Klingon word lookup\n") print("(F)lashcard Game - Randomly selected words in both Klingon and English\n") print("(T)ranslate\n") print("(C)ommon Phrases - Bootstrap your tlhngan Hol knowledge\n") print("(A)bout\n") print("(Q)uit\n") choice = input("Select an option from above:") if choice.upper() == 'P': print("FOO") elif choice.upper() == "T": Translator.translate(None) elif choice.upper() == 'F': Flashcard.loaddeck(20) elif choice.upper() == 'D': Dictionary.loadDictionary('dictionary') Dictionary.lookup(None) elif choice.upper() == 'C': CommonPhrases.loadPhrases() elif choice.upper() == 'Q': exit() else: print_menu()
def generateTestFeatures(self, pBatch): """Generate Test Features""" logger = logging.getLogger('GetFeatures::generateTestFeatures') logger.info("Generate Universal Features ") segmentFeaturesDict = self.generateFeatures(pBatch) if "translation" in pBatch and pBatch["translation"] == "yes": logger.info("Add Translation Features") pBatch["translationFile"] = re.sub( ".txt$", "", pBatch["segmentsFile"]) + "-translation.txt" tr = Translate(pBatch["segmentsFile"], pBatch["translationFile"], pBatch["sourceLanguage"], pBatch["targetLanguage"]) tr.addFeatures(segmentFeaturesDict) elif "hunalign" in pBatch and pBatch["hunalign"] == "yes": logger.info("Add HunAlign Features") ha = HunAlign(pBatch) ha.addFeatures(segmentFeaturesDict) elif "fastalign" in pBatch and pBatch["fastalign"] == "yes": logger.info("Add FastAlign Features") fa = FeaturesFastAlign(pBatch) fa.addFeatures(segmentFeaturesDict) elif "dictionary" in pBatch and pBatch["dictionary"] == "yes": logger.info("Add (Probabilistic) Dictionary Features") fTrDict = re.sub(".txt$", "", pBatch["segmentsFile"]) + "-dictionary.txt" dct = Dictionary(pBatch["segmentsLangFile"], fTrDict, pBatch["dictionaryFile"]) dct.addFeatures(segmentFeaturesDict) logger.info("Store Model File : " + pBatch["testFeatureFile"]) self.writeFeatureFile(pBatch["testFeatureFile"], segmentFeaturesDict)
def __buildArrayDictionary(self, member): ''' Build a dictionary that represents an array. The address will be the default of zero and can be set appropriately by the client. ''' #the variable "dictionary" is an instance of the class "Dictionary" which is located in "Dictionary.py" dictionary = Dictionary() dictionary.description('%s Array' % (member.type())) dictionary.address(0) object_size = 0 for i in range(member.number()): exec('object = Memory.%s()' % (member.type())) object_size = object.size() object.address(i * object_size) dictionary.addEntry(i, object) dictionary.size(object_size * member.number()) return(dictionary)
def __init__(self, ttx_interface, dictionary_manager, Nano=False): self.__current_tuner = CurrentTuner(ttx_interface) self.__power_tuner = PowerTuner() config = System.Configuration() if Nano: # NANO status_dictionary = { '11': 'CHANNEL_LOCK', '10': 'STABILIZE', '13': 'MZM_STATE', '12': 'FINE_TUNE', '1': 'IDLE', '0': 'COLD_START', '3': 'TEMPERATURE', '2': 'DARK', '5': 'ADJUSTMENT', '4': 'GAIN_MEDIUM', '7': 'CAVITY_LOCK', '6': 'FIRST_LIGHT', '9': 'CAVITY_OFFSET_LOCK', '8': 'POWER_LEVEL' } state_dictionary = { '1': 'POWER_STATE_LASER_PHOTODIODE', '0': 'POWER_STATE_DISABLE', '3': 'POWER_STATE_LOCK', '2': 'POWER_STATE_MZM_PHOTODIODE' } self.__current_tuner.statusDictionary(status_dictionary) self.__current_tuner.powerStateDictionary(state_dictionary) self.__power_tuner.statusDictionary(status_dictionary) self.__power_tuner.powerStateDictionary(state_dictionary) return status_dictionary = config.restore(ttx_interface.firmwareVersion(), 'TunerStatus') # print ttx_interface.firmwareVersion() if len(status_dictionary) == 0: raise 'TunerStatus undefined!' state_dictionary = config.restore(ttx_interface.firmwareVersion(), 'PowerState') if len(state_dictionary) == 0: raise 'Power States undefined!' dm = dictionary_manager d = Dictionary.Dictionary() # d.memory(dm.dictionary('MODEL_DICTIONARY').memory()) # d.addEntry('model', dm.dictionary('MODEL_DICTIONARY')) ###d.addEntry('ambient_compensator', dm.dictionary('AMBIENT_COMPENSATOR_DICTIONARY')) self.__current_tuner.statusDictionary(status_dictionary) self.__current_tuner.powerStateDictionary(state_dictionary) self.__current_tuner.dictionary(d) d1 = Dictionary.Dictionary() # d1.memory(dm.dictionary('MODEL_DICTIONARY').memory()) # d1.addEntry('model', dm.dictionary('MODEL_DICTIONARY')) ###d1.addEntry('power', dm.dictionary('POWER_DICTIONARY')) ###d1.addEntry('ambient_compensator', dm.dictionary('AMBIENT_COMPENSATOR_DICTIONARY')) self.__power_tuner.statusDictionary(status_dictionary) self.__power_tuner.powerStateDictionary(state_dictionary) self.__power_tuner.dictionary(d1)
def __init__(self, parentWindow, parentGame, parentCanvas): self.parentWindow = parentWindow self.parentGame = parentGame self.parentCanvas = parentCanvas self.items = {} self.wordsFound = [] self.language = parentWindow.language self.solver = parentWindow.solver self.graph = Graph(self.language) self.lettersList = self.graph.lettersList self.draw_hexagon(parentCanvas, 340, 95, 140) self.word = [] self.dico = Dictionary(self.language) self.solver = Solver(self.graph, self.dico, self.lettersList, self.solver) self.solutionSolver = self.solver.solution self.parentGame.insertListBox(self.solutionSolver) self.validationPolygon = parentCanvas.create_polygon(820, 0, 1030, 0, 1030, 180, 820, 180, fill='')
def __init__(self, name): """ptnaオブジェクトの名前をnameに格納 Respondeオブジェクトを生成してresponderに格納 @param name ptnaオブジェクトの名前 """ self.name = name # Dictionaryを生成 self.dictionary = Dictionary() # emotion を生成 self.emotion = Emotion(self.dictionary) # randomresponderを生成 self.res_random = RandomResponder('Random', self.dictionary) # RepeatResponderを生成 self.res_what = RepeatResponder('Repeat', self.dictionary) # PatternResponderを生成 self.res_pattern = PatternResponder('Pattern', self.dictionary) # Hadouresponderを生成 self.res_hadou = HasdouResponder('破道', self.dictionary) # Nogutiresponderを生成 self.res_Noguti = NogutiResponder('By野口', self.dictionary) # tyuusennを生成 self.res_tyuusenn = tyuusennResponder('抽選', self.dictionary) # ttyuusenn self.res_ttyuusenns = ttyuusennResponder('抽選', self.dictionary) # Template respondeer self.res_template = TemplateResponder('Template', self.dictionary) # 初期値をセット self.responder = self.res_what
def removeOneUser(self, username): dictionary = Dictionary.getUserDictionary() if username in dictionary: print("Deleted ", username) del dictionary[username] else: print(username, " not found.") Dictionary.writeUserDictionary(dictionary)
def example(): print("------Testing RSA------") print("\n\n") print("------Creating p & q------") p = createPrime() q = createPrime() print("p = ", p) print("q = ", q) print("\n\n") print("------Calculating n------") n = p * q print("n = ", n) print("\n\n") print("------Calculating Phi(n)------") phi = calculatingPhi(p, q) print("phi(n) = ", phi) print("\n\n") b = 0 while b == 0: print("------Finding a random which is prime with Phi(n)------") a = newRandom(phi) print("a = ", a) print("\n\n") print("------Calculating b=a^(-1) mod phi(n)------") ring = IntegerModRing(phi) b = ring.pow(a, -1) print("b = ", b) print("\n\n") print("------Encoding the message------") message = "Today, we are going to learn how to programm RSA in python3.6" print("uncoded message : ", message) print("\n\n") L = Dictionary.encoding(message) print(L) L2 = [] for _ in L: L2.append(encryption(_, n, a)) # print(L2) print("coded message : ", L2) print("\n\n") print("------Decoding the message------") L3 = [] for _ in L2: L3.append(encryption(_, n, b)) decodedMessage = Dictionary.decoding(L3) print("decoded message : ", decodedMessage) print("\n\n")
def importing(self): if pcapDumpPath != "": dictionary = logMerge.import_logs(pcapDumpPath) else: print("insert setPath() method properly here") pass Dictionary.writeUserDictionary(dictionary) new_dict = Dictionary.getUserDictionary() # does this happen here or in exporting()? i forgot self.update_pcap(new_dict)
def get_translation_from_dictionary(token): translations = Dictionary.match(token) if translations: translation = clean_word(translations[0].meanings[0]) return translation else: translations = Dictionary.get_proper_noun(token.root) if translations: return translations[0].meanings[0] else: return None
def main(): #print(len(sys.argv)) if len(sys.argv) == 7 and sys.argv[1] == '-MakeDictionary': firstLang = sys.argv[2] firstLangBiblePath = sys.argv[3] secondLang = sys.argv[4] secondLangBiblePath = sys.argv[5] dictionariesPath = sys.argv[6] MakeDictionary(firstLang, firstLangBiblePath, secondLang, secondLangBiblePath, dictionariesPath) if len(sys.argv) == 3 and sys.argv[1] == '-DownloadLibrary': path = sys.argv[2] DownloadLibrary(path) if len(sys.argv) == 7 and sys.argv[1] == '-AlignBooks': libraryPath = sys.argv[2] firstLang = sys.argv[3] secondLang = sys.argv[4] dictionariesPath = sys.argv[5] alignedBooksPath = sys.argv[6] AlignBooks(libraryPath, firstLang, secondLang, dictionariesPath, alignedBooksPath) if len(sys.argv) == 4 and sys.argv[1] == '-MakeTwoLangCorpus': alignedBooksPath = sys.argv[2] corpusPath = sys.argv[3] MakeTwoLangCorpus(alignedBooksPath, corpusPath) if len(sys.argv) == 1: dictionary1 = Dictionary.Dictionary() dictionary1.LoadFromFile( "C:\\Users\\Bober\\Desktop\\ботва\\8\\Мат СК\\Dictionaries_2\\EN-RU.xml" ) dictionary2 = Dictionary.Dictionary() dictionary2.LoadFromFile( "C:\\Users\\Bober\\Desktop\\ботва\\8\\Мат СК\\Dictionaries_2\\RU-EN.xml" ) aligner = Aligner.Aligner("EN", "RU", dictionary1, dictionary2) enSentence1 = "The emperor of Lilliput, attended by several of the nobility, comes to see the author in his confinement" ruSentence1 = "Император Лилипутии в сопровождении многочисленных вельмож приходит навестить автора в его заключении" print('-----Computing alignment value fo sentences:') print('1. ', enSentence1) print('2. ', ruSentence1) value1 = aligner._getSencencesAlignmentValue(enSentence1, ruSentence1) print(value1) enSentence2 = "I took them all in my right hand, put five of them into my coat-pocket; and as to the sixth, I made a countenance as if I would eat him alive" ruSentence2 = "Его императорское величество часто обращался ко мне с вопросами, на которые я отвечал ему, но ни он, ни я не понимали ни слова из того, что говорили друг другу" print('-----Computing alignment value fo sentences:') print('1. ', enSentence2) print('2. ', ruSentence2) value2 = aligner._getSencencesAlignmentValue(enSentence2, ruSentence2) print(value2)
def substituteWords(sentence): global klingonGrammar, pairs, grammarList kGrammar = klingonGrammar gList = grammarList print("---------Substituting Words---------") for noun in kGrammar['N']: print("Looking up:" + noun) ret = Dictionary.returnKlingon(noun) if ret is not None: #sentence = sentence.replace(noun, ret) kGrammar['N'][kGrammar['N'].index(noun)] = "\"" + ret + "\"" pairs.update({noun: ret}) #kGrammar['N'].remove(noun) else: print("Couldn't find:" + noun) for verb in klingonGrammar['V']: ret = Dictionary.returnKlingon(verb) if ret is not None: #sentence = sentence.replace(verb, ret) kGrammar['V'][kGrammar['V'].index(verb)] = "\"" + ret + "\"" pairs.update({verb: ret}) for prep in kGrammar['P']: ret = Dictionary.returnKlingon(prep) if ret is not None: #sentence = sentence.replace(prep, ret) kGrammar['P'][kGrammar['P'].index(prep)] = "\"" + ret + "\"" pairs.update({prep: ret}) for DET in klingonGrammar['Det']: ret = Dictionary.returnKlingon(DET) if ret is not None: #sentence = sentence.replace(DET, ret) kGrammar['Det'][kGrammar['Det'].index(DET)] = "\"" + ret + "\"" pairs.update({DET: ret}) for ADJ in kGrammar['Adj']: ret = Dictionary.returnKlingon(ADJ) if ret is not None: #sentence = sentence.replace(ADJ, ret) kGrammar['Adj'][kGrammar['Adj'].index(ADJ)] = "\"" + ret + "\"" pairs.update({ADJ: ret}) print("Klingon Grammar:" + str(klingonGrammar)) print("Glossed Sentence:" + sentence) sent = sentence.split(" ") for s in sent: print(s) sent[sent.index(s)] = pairs.get(s.strip()) print(sent) print(' '.join(sent)) return ' '.join(sent)
def search(): ret = str(request.args['query']) Dictionary.loadDictionary('dictionary') #retString = LoadDictionary.lookup(ret) ret = Dictionary.lookup(ret) retHtml = "" for item in ret: retHtml += "<div class='well well-sm'>" retHtml += str(item) retHtml += "</div>" return retHtml
def make_inverted_index(filename,read_buff_size,output_file_record_size,web_record_numbers=100000): ''' :param filename: 网页数据,包含后缀.txt :param read_buff_size:按块读文件,每个块的大小 :param output_file_token_size:输出每个文件中包含的新闻纪录数 :param 输入文件网页记录总数,用于显示程序处理进度 ,无其他用处 :return:倒排索引文件 ''' #读文件,分词,存储倒排索引至多个文件 block_read=read_block(read_buff_size,filename) punct = set(u'''/+%#:!),.:;?]}¢'"、。〉》」』】〕〗〞︰︱︳﹐、﹒ ﹔﹕﹖﹗﹚﹜﹞!),.:;?|}︴︶︸︺︼︾﹀﹂﹄﹏、~¢ 々‖•·ˇˉ―--′’”([{£¥'"‵〈《「『【〔〖([{£¥〝︵︷︹︻ ︽︿﹁﹃﹙﹛﹝({“‘-—_…''') Letters_and_numbers=set('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789') buff_dir=filename[:-4]+'_buff' #创建问价夹,用于存放 构建倒排索引过程中的中间文件,构建完成后删除文件夹 if os.path.exists(buff_dir): pass else: os.mkdir(buff_dir) file_numbers=1 while True: print "process :cuting word +making inverted_index files---->>>>",file_numbers*(output_file_record_size)*1.0/web_record_numbers spimi=SPIMI_Invert(buff_dir+'/'+str(file_numbers)+'.txt') count=0 while True: doc_id,content=block_read.pop_token() if content==''or count==output_file_record_size: break content_list=jieba.lcut_for_search(content) spimi.push_id(doc_id) for j in range(len(content_list)): if content_list[j] not in punct and content_list[j] not in Letters_and_numbers : spimi.push_word(content_list[j]) del content_list,doc_id,content count+=1 spimi.push_word('')#为空 表示写文件 file_numbers+=1 if content=='': break print ("process :cuting word +making inverted_index files---->>>>Finish") #合并倒排索引文件 merged_filename=merge_inverted_files.merge_file([str(i) for i in range(1,file_numbers)],read_buff_size,buff_dir+'/') print "process:mergeing inverted index files----->Finish" #由倒排索引文件构建 词-倒排索引位置 Dictionary.establish_ditionary(buff_dir+'/'+merged_filename+'.txt',read_buff_size,buff_dir+'/'+"Dictionary.txt") shutil.copy(buff_dir+'/'+merged_filename+'.txt',filename[:-4]+'_inverted_index.txt')#移动文件 shutil.copy(buff_dir+'/'+"Dictionary.txt",filename[:-4]+'_index_Dictionary.txt') shutil.rmtree(buff_dir)#删除文件夹 del merged_filename,buff_dir,punct,Letters_and_numbers
def manipulateData(columnNumber, dataset): """ Manipulates given data to create the data that will be tested @param {int} columnNumber: column index where the needed data is @param dataset: 2-D array of all data in the original file @returns Dictionary: object that contains the dictionary of UUID's """ #Make data the first colum and columnNumber column only uuid = dataset.at[0, columnNumber] newData = dataset.iloc[1:, 0: columnNumber + 1: columnNumber] timesColumn = dataset.loc[1:, 1] newData = newData.astype(float) newData = newData[~np.isnan(newData.iloc[:, 1])] newData.insert(loc = 0, column = "Time(UTC)", value = timesColumn) standardDeviationColumn = newData.iloc[:, 2].rolling(100).std() #Reset column index number to be sequential newData.columns = range(newData.shape[1]) #Create a new column and initialize values to 0 #lastColumn = dataset.iloc[:, dataset.shape[1] - 1] newData.insert(newData.shape[1], newData.shape[1], 0) newData.insert(newData.shape[1], newData.shape[1], 0) newData.insert(newData.shape[1], newData.shape[1], 0) #make new column as the previous value originalColumn = newData.loc[1:, 2] newData = newData.astype({3:'float64', 4:'float64', 5:'float64'}) for index in range(newData.index.shape[0] - 1): dataIndex = newData.index[index] newData.at[dataIndex, 3] = originalColumn.at[newData.index[index - 1]] newData.at[dataIndex, 4] = originalColumn.at[newData.index[index - 2]] newData.at[dataIndex, 5] = originalColumn.at[newData.index[index + 1]] newData = pd.DataFrame(newData) newData.insert(loc = newData.shape[1], column = "Standard Deviation", value = standardDeviationColumn) newData = newData.iloc[newData.index[99]: , :] #save the file as the testing dataset -- FOR TESTING testDataString = "TestingData/" + uuid + ".csv" newData.to_csv(testDataString) Dictionary.add(dataset.loc[0, columnNumber], newData) return newData
def __init__(self): title_file = open('title_list_wiki', 'r', encoding='utf-8') corpus_file = open('wiki_corpus', 'r', encoding='utf-8') titles = title_file.read().split('\a') documents = corpus_file.read().split('\a') while (True): index = int(input()) print(titles[index]) print(documents[index]) print(len(titles)) print(len(documents)) input() self.Dictionary = Dictionary.Dictionary() #데이터 파일과 Indexing File들이 저장 될 경로를 지정 self.path = '' file = open(self.path, 'r', encoding='utf-8') whole_text = file.read() documents = whole_text.split('\t') self.number_of_document = len(documents) for i in range(self.number_of_document): 0
def deleteCommonXpathsFromPageObjectRepo(commonELementsdic): files = [] for i in os.listdir("ObjectMap/"): i = "ObjectMap/" + i if i.endswith('.txt'): files.append(i) for filePath in files: elementsDic = Dictionary.readXpathsFromObjectRepo(filePath) for elementKey in elementsDic: for commonKey in commonELementsdic: if (elementKey == commonKey): try: elementsDic = { key: val for key, val in elementsDic.items() if key != elementKey } print("Deleted element " + commonKey + " from page " + filePath) except KeyError: pass df = pd.DataFrame([(k, v) for k, v in elementsDic.items()], columns=['key', 'value']) df.to_csv(filePath, sep=';')
def get_all_meanings(token): entries = Dictionary.match(token) proper_nouns = Dictionary.get_proper_noun(token.word) if entries is None and proper_nouns is None: return [] if proper_nouns is None: proper_nouns = [] if entries is None: entries = [] translations = [] for entry in entries: translations.extend(entry.meanings) for entry in proper_nouns: translations.extend(entry.meanings) translations = [Translator.clean_word(t).strip() for t in translations] return translations
def __init__(self, aCompanyInformationList, aBoWIDFDatabaseName, aIDFinanceClientIntelligent): self.status = "OPEN" self.companyinformationlist = aCompanyInformationList self.bowidfdbconnection = Helpers.TSSQLConnection(aBoWIDFDatabaseName) BoWIDFI.UpdateWord(self.bowidfdbconnection) BoWIDFI.UpdateArticle(self.bowidfdbconnection) BoWIDFI.UpdateWords(self.bowidfdbconnection) self.__createTables() self.intradayconnection = aIDFinanceClientIntelligent self.dictionary = Dictionary.Dictionary() self.parsepool = pool.Pool(processes=4) self.PaLQueue = queue.Queue() self.StopToken = "STOP" self.longlearnqueue = queue.Queue() self.workerThread = threading.Thread(target=self.__PaLWorker, name="IntelligentWorker") self.workerThread.start() self.poolLock = threading.RLock()
def interpret(self, string): """ Takes any input a given player has typed and acts out the action the input has requested. Interprets then executes. """ return Dictionary.interpret(self, string, self._interpreterMode)
def conjugatetable(): word = input("Conjugate a word (English to Klingon or Klingon to English:") #print("Conjugating " + word) if word == "": return word = Dictionary.returnword(word).split(":") print("First Person Singular:") firstsing = person.get('1st sing') print(firstsing) print('No Object:' + firstsing[0] + word[0] + " -- I " + word[1]) print('1st Singular:' + firstsing[1] + word[0] + " -- I " + word[1] + " (Myself)") print('2nd Singular:' + firstsing[2] + word[0] + " -- I " + word[1] + " You") print('3rd Singular:' + firstsing[3] + word[0] + " -- I " + word[1] + " Him/Her") print('1st Plural:' + firstsing[4] + word[0] + " -- I " + word[1] + " Us") print('2nd Plural:' + firstsing[5] + word[0] + " -- I " + word[1] + " You guys") print('3rd Plural:' + firstsing[6] + word[0] + " -- I " + word[1] + " Them") ret = "" firstsing = person.get('2nd sing') print('No Object:' + firstsing[0] + word[0] + " -- You " + word[1]) print('1st Singular:' + firstsing[1] + word[0] + " -- You " + word[1] + " Me") print('2nd Singular:' + firstsing[2] + word[0] + " -- You " + word[1] + " Yourself") print('3rd Singular:' + firstsing[3] + word[0] + " -- You " + word[1] + " Him/Her") print('1st Plural:' + firstsing[4] + word[0] + " -- You " + word[1] + " Us") print('2nd Plural:' + firstsing[5] + word[0] + " -- You " + word[1] + " Yourselves") print('3rd Plural:' + firstsing[6] + word[0] + " -- You " + word[1] + " Them") return ret
def on_button3_clicked(self): self.clear() os.system('UI_2\XiaoZhi.py') #f=open('E:/biancheng/Python/AOM/outcome/xiaozhi_text/input.txt', 'r', encoding = 'utf-8') # lines = f.readlines() # data = lines[-1] #f.close() outcome = Dictionary.audio(open("outcome/xiaozhi_text/input.txt",'r',encoding='utf-8')) emo = outcome[-1] if emo == 0: file_music ='data/audio/xiaozhi/no_emo.mp3' elif emo<0: file_music ='data/audio/xiaozhi/sad.mp3' elif emo >0: file_music ='data/audio/xiaozhi/pleasant.mp3' result = file_music pygame.mixer.init() pygame.mixer.music.load(result) pygame.mixer.music.play() self.outcome3 = [] self.clearLine3 = [] self.txt3=open('outcome/record.txt', 'r', encoding = 'utf-8') for line in self.txt3: if not line == '/n': self.outcome3.append(line) for l in range(0, len(self.outcome3)): self.clearLine3.append('') self.txt3.close() self.xiaozhiButton1 = True self.xiaozhi_button2.show() print(outcome)
async def _define(channel, word): embed = discord.Embed() definition = Dictionary.definition(word) # Set embed to error message if no definition is found if not definition: embed.color = 0xFF0000 # Red embed.title = "Unable to find a definition for '" + word + "'" # Set embed to noun or verb definitions else: embed.color = 0x00FF00 # Green embed.title = "Here is what I found for '" + word + "'" try: noun = definition['Noun'][0] + "\n\n" embed.add_field(name="Noun:", value=noun, inline=False) except: pass try: verb = definition['Verb'][0] + "\n\n" embed.add_field(name="Verb:", value=verb, inline=False) except: pass await channel.send(embed=embed)
def parseEntry(self, fileList): """ Parses file names. Creates Dictionary of files to be transfered to Tecnomatix format and dictionary of unparsed entries. """ entryType = "" dictionary = Dictionary.readFromFile() self.transformDict = {} self.unresolvedDict = {} for entry in fileList: path = entry fileName = entry.split('/')[-1] flag = False for key, val in dictionary.items(): for pattern in val: match = re.search(pattern, fileName, flags=re.IGNORECASE) if match: # print("match") flag = True self.transformDict[path] = key break if flag: break if not flag: self.unresolvedDict[path] = fileName
def getDefinitions(self): """ Get associated definition(s) for this word """ if self._definitions == None: import Dictionary self._definitions = Dictionary.getDefinitions(self.wordName) return self._definitions
def synonyms(): ret = str(request.args['query']) html = "" synonyms = Dictionary.find_synonyms(ret) for syn in synonyms: html = html + "<li class='list-group-item'>" + str(syn) + "</li>" print(syn) return html
def generateTrainingFeatures(self): """Generate Training Features.""" logger = logging.getLogger('GetFeatures::generateTrainingFeatures') logger.info("Detect Source and Target Languages ") self.pDict["segmentsFile"] = re.sub( ".txt$", "", self.pDict["fCategory"]) + "-segments.txt" self.removeCategory() self.getLanguageForSegmentFile() logger.info("Generate Universal Features ") segmentFeaturesDict = self.generateFeatures(self.pDict) if "translation" in self.pDict and self.pDict["translation"] == "yes": logger.info("Add Translation Features") fTranslations = re.sub( ".txt$", "", self.pDict["fCategory"]) + "-translation.txt" tr = Translate(self.pDict["fCategory"], fTranslations, self.pDict["sourceLanguage"], self.pDict["targetLanguage"]) tr.addFeatures(segmentFeaturesDict) elif "hunalign" in self.pDict and self.pDict["hunalign"] == "yes": logger.info("Add HunAlign Features") ha = HunAlign(self.pDict) ha.addFeatures(segmentFeaturesDict) elif "fastalign" in self.pDict and self.pDict["fastalign"] == "yes": logger.info("Add FastAlign Features") fa = FeaturesFastAlign(self.pDict) fa.addFeatures(segmentFeaturesDict) elif "dictionary" in self.pDict and self.pDict["dictionary"] == "yes": logger.info("Add (Probabilistic) Dictionary Features") fTrDict = re.sub(".txt$", "", self.pDict["fCategory"]) + "-dictionary.txt" dct = Dictionary(self.pDict["segmentsFile"], fTrDict, self.pDict["dictionaryFile"]) dct.addFeatures(segmentFeaturesDict) logger.info("Add the category for the Training Set") self.addCategory(segmentFeaturesDict) logger.info("Store Model File : " + self.pDict["trainingFeatureFile"]) self.writeFeatureFile(self.pDict["trainingFeatureFile"], segmentFeaturesDict)
def inverted_index(filename,read_buff_size,output_file_record_size): ''' :param filename: 网页数据,包含后缀.txt :param read_buff_size:按块读文件,每个块的大小 :param output_file_token_size:输出每个文件中包含的新闻纪录数 :return:倒排索引文件 ''' ''' 读文件,分词,存储倒排索引至多个文件 ''' block_read=read_block(read_buff_size,filename) punct = set(u''':!),.:;?]}¢'"、。〉》」』】〕〗〞︰︱︳﹐、﹒ ﹔﹕﹖﹗﹚﹜﹞!),.:;?|}︴︶︸︺︼︾﹀﹂﹄﹏、~¢ 々‖•·ˇˉ―--′’”([{£¥'"‵〈《「『【〔〖([{£¥〝︵︷︹︻ ︽︿﹁﹃﹙﹛﹝({“‘-—_…''') file_numbers=1 while True: spimi=SPIMI_Invert(filename[:-4]+str(file_numbers)+'.txt') count=0 while True: doc_id,content=block_read.pop_token() if content==''or count==output_file_record_size: break content_list=jieba.lcut_for_search(content) spimi.push_id(doc_id) for j in range(len(content_list)): if content_list[j] not in punct: spimi.push_word(content_list[j]) del content_list,doc_id,content count+=1 spimi.push_word('')#为空 表示写文件 if content=='': break file_numbers+=1 ''' 合并倒排索引文件 ''' merged_filename=merge_inverted_files.merge_file([str(i) for i in range(1,file_numbers)],buff_size,filename[:-4]) ''' 由倒排索引文件构建 词-倒排索引位置 ''' Dictionary.establish_ditionary(filename[:-4]+merged_filename+'.txt',buff_size,filename[:-4]+"Dictionary.txt") ''' 加载存储的词典 ''' Dictionary.dictionary(filename[:-4]+"Dictionary.txt",filename[:-4]+merged_filename+'.txt',1024*1024)
def del flash move from default="mount" -> (".name") test_mode(optional index) <local> monut(dict) <local> new Dictionary(name) ===========
def MakeDictionary(firstLang, firstLangBiblePath, secondLang, secondLangBiblePath, dictionariesPath): dictionary = Dictionary.Dictionary() val = dictionary.LoadFromBibles(firstLang, firstLangBiblePath, secondLang, secondLangBiblePath) dictFilePath = os.path.join(dictionariesPath, firstLang + '-' + secondLang + '.xml') print(dictFilePath) dictionary.WriteToFile(dictFilePath)
def __init__(self): gtk.glade.XML.__init__(self, 'resources/glade/WordUp.glade', 'main_window') self.signal_autoconnect(self) self.main_window.connect('destroy', self.on_quit_activate) self.dictionary = Dictionary.Dictionary('resources/dictionaries/twl_split') self.top_score_manager = TopScoreManager.TopScoreManager() self.game = self.get_game() self.refresh_ui() timer = gobject.timeout_add(1000, self.update_time)
def arrange(self): keys = self.keys() objects = Dictionary() for i in keys: object_type = self.classify(i) if object_type not in objects: objects + (object_type, []) objects[object_type].append(i) return objects
def isVerb(self , word): #if the word is already in dictionary if (Dictionary.getA(word) == "verb"): return True #If the word have ING or ED at end if(word.endswith("ed") or word.endswith("ing")): #if the word is not in dictionary , go and add it #LEARNING TODO return True #ANOTHER WAY ? TODO return False
def is_word(candidate): entries = Dictionary.get(candidate.word) if entries is None: return False else: for entry in entries: for pos in entry.pos: if conjugates(pos) or might_be_copula(pos, candidate): return True return False
def __init__(self, do_post_processing=False, do_indexing=False): self.Data_holder = Dictionary.Dictionary( do_post_processing=do_post_processing, do_indexing=do_indexing) self.Extension_Memory = Extension_memory(3000) self.Frequency = np.zeros(shape=[self.Data_holder.Documents_Num], dtype=np.float32) self.Num_Words = np.zeros(shape=[self.Data_holder.Documents_Num], dtype=np.float32) print('start!')
def _merge_words_using_dictionary(tokens): merged = [] i = 0 while i + 1 < len(tokens): to_add = Token(tokens[i].word, tokens[i].grammar, tokens[i].root, tokens[i].char_indices, tokens[i].endings) start = i combination = tokens[i].word + tokens[i + 1].word combination = normalize_numbers(combination) combined_words = [tokens[i].word] dict_entry = Dictionary.match(Token(combination), match_pos=False) fails = 0 fail_limit = 2 # this setting dictates how far the system will look ahead to find valid combinations while fails < fail_limit: if dict_entry and should_merge(combined_words, combination, dict_entry): to_add.char_indices = [ tokens[start].char_indices[0], tokens[i + 1].char_indices[1] ] to_add.root = dict_entry[0].writings[0] to_add.pos = dict_entry[0].pos[0] to_add.word = combination fails = 0 else: fails += 1 i += 1 if i + 1 == len(tokens): break combination += tokens[i + 1].word combination = normalize_numbers(combination) combined_words.append(tokens[i].word) dict_entry = Dictionary.match(Token(combination), match_pos=False) merged.append(to_add) i += 1 - fails merged.append(tokens[i]) return merged
def main(): print("""MENU: (T)ranslate (P)revious screen (H)ome screen (Q)uit """) choice = input("What would you like to do?") if choice.upper() == "T": translate(None) elif choice.upper() == "P": if previous.upper == "VERBS": Verbs.main() elif previous.upper == "DICTIONARY": Dictionary.main() # elif previous.upper == "HOME": # KlingonTranslator.main() else: main()
def InitGame(self, event=None): self.dictionary = Dictionary.Dictionary('resources/dictionaries/twl_split') self.top_score_manager = TopScoreManager.TopScoreManager() data_dir = self.GetDataDir() if not os.path.exists(data_dir): try: os.makedirs(data_dir) except Exception as e: sys.stderr.write('Could not create data directory: %s\n' % data_dir) data_dir = None self.top_score_manager.set_data_dir(data_dir) self.game = self.get_game()
def main(): wordToGesture = Dictionary.wordToGesture() listener = SwypeListener() controller = Leap.Controller() controller.add_listener(listener) # Keep this process running until Enter is pressed print "Press Enter to quit..." sys.stdin.readline() # Remove the listener when done controller.remove_listener(listener)
def loaddeck(numcards): global deck tempDict = OrderedDict(Dictionary.loadDictionary("klingon")) tempDeck = [] for key, value in tempDict.items(): item = {key, value} tempDeck.append(item) x = 0 while x < numcards: num = random.randrange(0, len(tempDeck) - 1) deck.append(tempDeck[num]) del (tempDeck[num]) x += 1 menu()
def CosineScore(query_token_list,Topk_numbers=10): ''' 查询词项:w=log(N/df) 文档词项:w=(1+logtf) :param query_token_list: :return: ''' dictionary=Dictionary.dictionary("data/netease_dataDictionary.txt","data/netease_data_inverted_index.txt",1024*1024*10) doc={} #key:doc_id value:position scores=[] #[score,doc_id,tf] for i in range(len(query_token_list)): term=query_token_list[i] df,doc_id,tf=dictionary.get_idfANDinvertedindex(term) w_query=math.log10(df) for j in range(len(doc_id)): w_d=1+math.log10(tf[j]) if doc.has_key(doc_id[j]): position=doc[doc_id[j]] scores[position][0]+=w_d*w_query scores[position][1]=doc_id[j] scores[position][2]+=(w_d**2) else: position=len(scores) doc[doc_id[j]]=position scores.append([w_d*w_query,doc_id[j],w_d**2]) for k in range(len(scores)): scores[k][0]=scores[k][0]/(scores[k][2]**0.5) max_quene=queue(scores) max_quene.build_quene2() topK=[] i=0 while True: id=max_quene.extract_max()[1] if id==-1 or i==Topk_numbers: break i+=1 topK.append(id) return topK
def main(argv): separator = ' ' # read m(# of constraints) and n(# of variables) m, n = toInt(readLine(sys.stdin, separator)) if DEBUG: sys.stderr.write(str(m)+"\n") sys.stderr.write(str(n)+"\n") # read the list of basic indices basicIdx = toInt(readLine(sys.stdin, separator)) if DEBUG: sys.stderr.write(str(basicIdx)+"\n") # read the list of non-basic indices nonBasicIdx = toInt(readLine(sys.stdin, separator)) if DEBUG: sys.stderr.write(str(nonBasicIdx)+"\n") # read the list of values for the basic indices (at the same order they are declared) # remember: Ax <= b, b is the list being read basicValues = toFloat(readLine(sys.stdin, separator)) if DEBUG: sys.stderr.write(str(basicValues)+"\n") # read the matrix A (from problem Ax <= b) coeffMatrix = [] for i in range(m): row = toFloat(readLine(sys.stdin, separator)) coeffMatrix.append(row) coeffMatrix = np.array(coeffMatrix) if DEBUG: sys.stderr.write(str(coeffMatrix)+"\n") # read the current objective value and the current objective row coefficients coeffObjs = toFloat(readLine(sys.stdin, separator)) z = coeffObjs[0] coeffObj = coeffObjs[1:] dictionary = Dictionary(m, n, basicIdx, nonBasicIdx, basicValues, coeffMatrix, coeffObj, z, mp.power(10,-100)) if DEBUG: sys.stderr.write("Original Dictionary\n") sys.stderr.write(str(dictionary)+"\n") # Initialization Phase newDictionary = dictionary.initialDictionary() if DEBUG: sys.stderr.write("Dictionary After Initialization Phase\n") sys.stderr.write(newDictionary+"\n") sys.stdout.flush() if newDictionary.statuscode == Dictionary.INFEASIBLECODE: sys.stdout.write(newDictionary.status) return opt = Optimizer() cuts, optmizedDict, status = opt.solveLinearProgrammingRelaxation(newDictionary) if DEBUG: sys.stderr.write("Ootimized Dictionary\n") sys.stderr.write(str(optmizedDict)+"\n") if optmizedDict.statuscode < 0: sys.stdout.write(status) else: print "%.6f" % optmizedDict.z
def __init__(self): self.Alphabet = string.ascii_lowercase self.WordList = Dictionary.dictionary() self.UsedList = [] self.Cont = False self.LegalChange = False self.PlayerTurn = True self.GameOn = True self.giveUp = False print """ Welcome to the Word Changing Game. In this game you type a word to start with, and then we take turns changing that word to another word with one change. It can be a replacement, insertion, or deletion, but it can only be of one letter. Whoever cannot come up with another word loses. If you can't think on one, type "I give up" and we'll end. Let's begin!""" while self.GameOn: while self.PlayerTurn: self.NewWord = raw_input("Player: ").lower().strip() if self.NewWord == "i give up": self.GameOn = False self.giveUp = True self.PlayerTurn = False self.changeWord() if self.PlayerTurn == False: print "There was no other word you could have used. Good try!" break if self.NewWord in self.WordList and self.NewWord not in self.UsedList: if len(self.UsedList) == 0: # if this is the first word self.UsedList.append(self.NewWord) self.OldWord = self.NewWord self.PlayerTurn = False else: # establishes a legal change, already established that word is known for index in range(0, len(self.OldWord)+1): for character in self.Alphabet: self.TestWord = self.OldWord[:index] + character + self.OldWord[index + 1:] # replace if self.TestWord == self.NewWord: self.LegalChange = True break self.TestWord = self.OldWord[:index] + character + self.OldWord[index:] # insert if self.TestWord == self.NewWord: self.LegalChange = True break if not self.LegalChange: self.TestWord = self.OldWord[:index] + self.OldWord[index+1:] # delete if self.TestWord == self.NewWord: self.LegalChange = True if self.LegalChange: self.OldWord = self.NewWord self.UsedList.append(self.NewWord) self.LegalChange = False self.PlayerTurn = False break if self.PlayerTurn: print "that was not a legal change. The word to change is %s" % self.OldWord elif self.NewWord in self.UsedList: print "that word has already been used. The word to change is %s" % self.OldWord else: print "that's not a recognized word. The word to change is %s" % self.OldWord while not self.PlayerTurn and not self.giveUp: self.changeWord() if not self.PlayerTurn: # computer can't find another word print "Congratulations, you win!" self.GameOn = False break
| | o_ | | | / \ | __|__""" if badguess == 6: print """ ______ | | _o_ | | | / \ | __|__""" print "You hung him! The word was '%s' \n Why don't you try this one?" % (word) words = Dictionary.dictionary() print "Pybot: Welcome to Hangman!" win = input("How many words would you like to play to win:") while win < 0 or win > 57949: win = input("I'm sorry, please type in an integer less than or equal to 57949 and more than 0:") if win == 0: break print "Ok, Here's the first one for you!" q = 1 wincompare = 0 while q == 1: word = random.choice(words) badguess = 0 usedlistwrong = "" UnusedLetters = string.lowercase # this from string import looping = len(word)
def synonyms(): ret = str(request.args['query']) return Dictionary.find_synonyms(ret)
def compareResults(oldJson, newJson): # # initialize the differences structure and local copies of the publication metadata and the manifest for comparison # jsonDelta = {} jsonDelta["summary"] = {} jsonDelta["summary"]["newCheck"] = newJson["checker"] jsonDelta["summary"]["oldCheck"] = oldJson["checker"] jsonDelta["publication"] = {} jsonDelta["publication"]["adds"] = {} jsonDelta["publication"]["cuts"] = {} jsonDelta["publication"]["changes"] = {} jsonDelta["manifest"] = {} jsonDelta["manifest"]["adds"] = {} jsonDelta["manifest"]["cuts"] = {} jsonDelta["manifest"]["changes"] = {} jsonDelta["spine"] = {} jsonDelta["spine"]["adds"] = {} jsonDelta["spine"]["cuts"] = {} jsonDelta["spine"]["orderChanges"] = {} jsonDelta["spine"]["contentChanges"] = [] jsonDelta["spine"]["unchanged"] = 0 oldPub = oldJson["publication"] newPub = newJson["publication"] newSpine = {} newSpineContents = {} oldSpineContents = {} oldSpine = {} newMani = newJson["items"] oldMani = oldJson["items"] newManiDict = Dictionary.makeDict(newMani, "id") oldManiDict = Dictionary.makeDict(oldMani, "id") # # compare the publication metadata # deltaPub = Dictionary.DictCompare(newPub, oldPub) for item in deltaPub.added(): jsonDelta["publication"]["adds"][item] = newPub[item] for item in deltaPub.removed(): jsonDelta["publication"]["cuts"][item] = oldPub[item] pubChanges = deltaPub.changed() if len(pubChanges) > 0: for item in pubChanges: jsonDelta["publication"]["changes"][item] = {"newValue" : newPub[item], "oldValue" : oldPub[item]} if len(jsonDelta["publication"]["adds"]) + len(jsonDelta["publication"]["cuts"]) + len(jsonDelta["publication"]["changes"]) == 0: pubChanges = "Pub==" else: pubChanges = "Pub-" if len(jsonDelta["publication"]["adds"]) > 0: pubChanges += "A" + str(len(jsonDelta["publication"]["adds"])) else: pubChanges += "xA" if len(jsonDelta["publication"]["cuts"]) > 0: pubChanges += "-R" + str(len(jsonDelta["publication"]["cuts"])) else: pubChanges += "-xR" if len(jsonDelta["publication"]["changes"]) > 0: pubChanges += "-C" + str(len(jsonDelta["publication"]["changes"])) else: pubChanges += "-xC" jsonDelta["summary"]["publicationChanges"] = len(jsonDelta["publication"]["adds"]) + len(jsonDelta["publication"]["cuts"]) + len(jsonDelta["publication"]["changes"]) jsonDelta["summary"]["encodedPubChanges"] = pubChanges # print(" Calculated publication changes: adds: " + str(len(jsonDelta["publication"]["adds"])) + "; cuts: " + str(len(jsonDelta["publication"]["cuts"])) + "; changes: " + str(len(jsonDelta["publication"]["changes"]))) # # compare the spines # for item in newMani: if item["isSpineItem"]: newSpine[item["id"]] = item["spineIndex"] newSpineContents[item["id"]] = item["checkSum"] for item in oldMani: if item["isSpineItem"]: oldSpine[item["id"]] = item["spineIndex"] oldSpineContents[item["id"]] = item["checkSum"] deltaSpine = Dictionary.DictCompare(newSpine, oldSpine) deltaSpineContents = Dictionary.DictCompare(newSpineContents, oldSpineContents) # # look for adds/cuts/order changes in the spine # if len(deltaSpine.added()) > 0: for item in deltaSpine.added(): jsonDelta["spine"]["adds"][item] = newSpine[item] if len(deltaSpine.removed()) > 0: for item in deltaSpine.removed(): jsonDelta["spine"]["cuts"][item] = oldSpine[item] if len(deltaSpine.changed()) > 0: jsonDelta["spine"]["orderChanges"] = {} for item in deltaSpine.changed(): jsonDelta["spine"]["orderChanges"][item] = {} jsonDelta["spine"]["orderChanges"][item]["newSpineIndex"] = newSpine[item] jsonDelta["spine"]["orderChanges"][item]["oldSpineIndex"] = oldSpine[item] jsonDelta["spine"]["unchanged"] = len(deltaSpine.unchanged()) # # look for content changes only in items common to both spines # if len(deltaSpineContents.changed()) > 0: for item in deltaSpineContents.changed(): jsonDelta["spine"]["contentChanges"] = {} jsonDelta["spine"]["contentChanges"][item] = newManiDict[item]["fileName"] # # summarize the spine changes # if len(jsonDelta["spine"]["adds"]) + len(jsonDelta["spine"]["cuts"]) + len(jsonDelta["spine"]["orderChanges"]) + len(jsonDelta["spine"]["contentChanges"]) == 0: spineChanges = "Spine==-N" + str(newPub["nSpines"]) else: spineChanges = "Spine-N" + str(newPub["nSpines"]) if jsonDelta["spine"]["unchanged"] == 0: spineChanges += "-xU" else: spineChanges += "-U" + str(jsonDelta["spine"]["unchanged"]) if len(jsonDelta["spine"]["adds"]) > 0: spineChanges += "-A" + str(len(jsonDelta["spine"]["adds"])) else: spineChanges += "-xA" if len(jsonDelta["spine"]["cuts"]) > 0: spineChanges += "-R" + str(len(jsonDelta["spine"]["cuts"])) else: spineChanges += "-xR" if len(jsonDelta["spine"]["orderChanges"]) > 0: spineChanges += "-OC" + str(len(jsonDelta["spine"]["orderChanges"])) else: spineChanges += "-xOC" if len(jsonDelta["spine"]["contentChanges"]) > 0: spineChanges += "-CC" + str(len(jsonDelta["spine"]["contentChanges"])) else: spineChanges += "-xCC" jsonDelta["summary"]["spineChanges"] = len(jsonDelta["spine"]["adds"]) + len(jsonDelta["spine"]["cuts"]) + len(jsonDelta["spine"]["orderChanges"]) + len(jsonDelta["spine"]["contentChanges"]) jsonDelta["summary"]["encodedSpineChanges"] = spineChanges # # do the manifest # deltaMani = Dictionary.DictCompare(newManiDict, oldManiDict) for item in deltaMani.added(): jsonDelta["manifest"]["adds"][item] = newManiDict[item] for item in deltaMani.removed(): jsonDelta["manifest"]["cuts"][item] = oldManiDict[item] maniChanges = list(deltaMani.changed()) if (len(maniChanges)) > 0: for item in maniChanges: itemDelta = {} deltaItem = Dictionary.DictCompare(newManiDict[item], oldManiDict[item]) if len(deltaItem.added()) > 0: itemDelta["adds"] = {} for theAdd in deltaItem.added(): #print("property added: " + theAdd + " value: " + str(newManiDict[item][theAdd])) itemDelta["adds"][theAdd] = newManiDict[item][theAdd] if len(deltaItem.removed()) > 0: itemDelta["cuts"] = {} for theCut in deltaItem.removed(): itemDelta["cuts"][theCut] = oldManiDict[item][theCut] if len(deltaItem.changed()) > 0: itemDelta["changes"] = {} for itemProp in deltaItem.changed(): if itemProp == "referencedItems": oldRefs = set(oldManiDict[item][itemProp]) newRefs = set(newManiDict[item][itemProp]) refsCommon = newRefs & oldRefs refsAdded = newRefs - oldRefs refsRemoved = oldRefs - refsCommon itemDelta["changes"][itemProp] = { "adds" : list(refsAdded), "cuts" : list(refsRemoved) } elif itemProp == "checkSum": itemDelta["changes"][itemProp] = {"newValue" : newManiDict[item]["fileName"], "oldValue" : oldManiDict[item]["fileName"]} else: itemDelta["changes"][itemProp] = {"newValue" : newManiDict[item][itemProp], "oldValue" : oldManiDict[item][itemProp]} jsonDelta["manifest"]["changes"][item] = itemDelta #print(" Manifest item id : " + item + " changed...") #print(" Manifest item delta: " + str(itemDelta)) # print(" Calculated manifest changes: adds: " + str(len(jsonDelta["manifest"]["adds"])) + "; cuts: " + str(len(jsonDelta["manifest"]["cuts"])) + "; changes: " + str(len(jsonDelta["manifest"]["changes"]))) jsonDelta["summary"]["itemChanges"] = len(jsonDelta["manifest"]["adds"]) + len(jsonDelta["manifest"]["cuts"]) + len(jsonDelta["manifest"]["changes"]) if jsonDelta["summary"]["itemChanges"] == 0: jsonDelta["summary"]["encodedManiChanges"] = "Mani==" else: maniChanges = "Mani-" if len(jsonDelta["manifest"]["adds"]) > 0: maniChanges += "A" + str(len(jsonDelta["manifest"]["adds"])) else: maniChanges += "xA" if len(jsonDelta["manifest"]["cuts"]) > 0: maniChanges += "-R" + str(len(jsonDelta["manifest"]["cuts"])) else: maniChanges += "-xR" if len(jsonDelta["manifest"]["changes"]) > 0: maniChanges += "-C" + str(len(jsonDelta["manifest"]["changes"])) else: maniChanges += "-xC" jsonDelta["summary"]["encodedManiChanges"] = maniChanges return(jsonDelta)
def on_init(self, controller): self.wordToGesture = Dictionary.wordToGesture() self.wordToFrequency = Dictionary.wordToFrequency() self.path = [] print "Initialized"
from Dictionary import * from Document import * teste = Dictionary("asdf") #print("eh assim msm"+teste.dicionario[0]) teste.structureDictionary() print(teste.dictionaryMatrix) print(teste.dictionaryList) #print("teste") testeDocument = Document("asdf") testeDocument.openDocument() print(testeDocument.document)