def play(): jugando = True Intentos = 7 jugando = [True, Intentos] listapalabras = DarIncongnita.DarIncognitaDesdeArchivo( ) #Hacer desde otra funcion para no llamar la lista del archivo cada vez que se llame esta funcion palaacer = [] #Crea una lista de palabras acertadas puntuacion = -1 while jugando[0]: puntuacion = puntuacion + 1 jugando, listapalabras, palaacer = playMatch(jugando[1], listapalabras, palaacer, puntuacion) #aca va venir el tema de guardar la puntuacion #pedir nombre y eso. nombre = Ranking.pedir_ingreso_nombre() Puntuacion_a_Guardar = Ranking.crear_tupla_nombre_puntos( nombre, puntuacion) listaPuntos_aGuardar = Ranking.meter_nueva_puntuacion_a_lista( Puntuacion_a_Guardar, Ranking.CargarRanking()) Ranking.GuardarRanking(listaPuntos_aGuardar)
def main_screen(): pygame.mouse.set_visible(True) start_image = pygame.image.load('main.png') pygame.display.set_caption('수룡 게임 천국') screen.blit(start_image, [0, 0]) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_1: PySpaceShip.main_loop() return 'main_screen' elif event.key == pygame.K_2: racingcar.main_loop() return 'main_screen' elif event.key == pygame.K_3: PyShooting.initGame() PyShooting.runGame() return 'main_screen' elif event.key == pygame.K_4: Ranking.main_loop() return 'main_screen' elif event.key == pygame.K_5: windowsC.main_loop() return 'main_screen' if event.type == QUIT: return 'quit' return 'main_screen'
class SaveAs(QtGui.QWidget): def __init__(self): QtGui.QWidget.__init__(self) self.setupUi(self) def setupUi(self, Form): self.Rank = Ranking() Form.setObjectName(_fromUtf8("Form")) Form.resize(70, 20) p = self.palette() p.setColor(self.backgroundRole(), QtCore.Qt.darkRed) self.setPalette(p) font = QtGui.QFont() font.setFamily(_fromUtf8("MS UI Gothic")) font.setPointSize(10) font.setBold(True) font.setWeight(75) self.Layout = QtGui.QVBoxLayout(Form) self.Layout.setObjectName(_fromUtf8("verticalLayout")) self.texto = QtGui.QLabel(Form) self.texto.setFont(font) self.texto.setText('GAME OVER') self.Layout.addWidget(self.texto) self.puntos = QtGui.QLabel(Form) self.puntos.setFont(font) self.puntos.setText('SCORE: {}'.format('0')) self.Layout.addWidget(self.puntos) self.User = QtGui.QLineEdit(Form) self.User.setObjectName(_fromUtf8("plainTextEdit")) self.Layout.addWidget(self.User) self.buttonBox = QtGui.QDialogButtonBox(Form) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok) self.buttonBox.setObjectName(_fromUtf8("buttonBox")) self.Layout.addWidget(self.buttonBox) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.buttonBox.clicked.connect(self.IngresarNombre) shortcut = QtGui.QShortcut(QtGui.QKeySequence("Enter"), self, self.IngresarNombre) shortcut.setContext(QtCore.Qt.WidgetShortcut) def retranslateUi(self, Form): Form.setWindowTitle(_translate("Game Over", "Game Over", None)) def setPuntaje(self, puntaje, time, mensaje=None): if mensaje is not None: self.texto.setText(mensaje) self.puntaje = str(puntaje) self.time = time self.puntos.setText('SCORE: {0}\n Time: {1}'.format(self.puntaje, self.time)) def IngresarNombre(self): usuario = self.User.text() if len(usuario) > 0: Data = SaveData(usuario, self.puntaje, self.time) self.Rank.setRanking(Data, usuario) self.Rank.show() self.hide()
async def getRanking(ctx): #userID = str(ctx.message.author.id) avatarLink = str(ctx.author.avatar_url) userName = ctx.author.name Ranking.createRankingCard(avatarLink, userName, str(ctx.author.id)) await ctx.send((ctx.message.author.mention), file=discord.File('ranking.png')) os.system('rm ranking.png') os.system('rm avatar.png')
def testCreateFPLink(self): self.assertEqual('http://www.fantasypros.com/nfl/rankings/ros-qb.php?export=xls', Ranking.create_standard_link('QB')) self.assertEqual('http://www.fantasypros.com/nfl/rankings/ros-ppr-te.php?export=xls', Ranking.create_ppr_link('TE')) self.assertEqual([('standard', 'http://www.fantasypros.com/nfl/rankings/ros-' 'wr.php?export=xls'), ('half_ppr', 'http://www.fantasypros.com/nfl/rankings/ros-' 'half-point-ppr-wr.php?export=xls'), ('ppr', 'http://www.fantasypros.com/nfl/rankings/ros-' 'ppr-wr.php?export=xls')], Ranking.create_all_links('WR'))
def drawPictures(): rank = Ranking.ranking() rank.loadAll() queries = formQueries() result = defaultdict(list) for query in queries: score = getRankScores(rank, query) result['queryID'].append(query.ID) result['precision'].append(precision(query, score, 10)) result['averagePrecision'].append(averagePrecision(query, score, 10)) result['precisionRecall'].append(precisionRecall(query, score)) plt.plot(result['queryID'], result['precision'],'ro', label="Precision") plt.plot(result['queryID'], result['averagePrecision'],'bo', label="averagePrecision") plt.plot(result['queryID'], result['precisionRecall'],'yo', label="precisionRecall") plt.axis([0, len(result['queryID']), 0, 0.6]) plt.xlabel('Query ID') plt.ylabel('Value') plt.legend() plt.savefig('rst.png') print "Overall Averaged Precision: " + str(sum(result['precision']) / len(queries)) plt.show()
def IRTest(texts, ir, num_cluster, percentage): kmeans = KMeans(n_clusters=num_cluster).fit(ir.corpus.TFIDF) label = list(zip(kmeans.labels_, range(len(texts)))) test = [] for cluster in range(num_cluster): #siapkan untuk summarization label_doc = list(filter(lambda x : x[0] == cluster, label)) label_text = [texts[label_doc[i][1]] for i in range(len(label_doc))] label_tfidf = np.array([ir.corpus.TFIDF[label_doc[i][1]] for i in range(len(label_doc))]) summa = Ranking.TextRank(label_tfidf).summarize(label_text, percentage) #retrive doc dengan query summa retrieved = [doc[0] for doc in ir.query(summa, len(label_doc))] #hitung confusion matrix dic_label = {page[1]:True for page in label_doc} dic_retrieved = {page:True for page in retrieved} TP = sum([1 if page in dic_label else 0 for page in retrieved]) FP = sum([1 if page not in dic_label else 0 for page in retrieved]) FN = sum([1 if page not in dic_retrieved else 0 for page in label_doc]) #hitung recall dan precision precision = float(TP) / (TP + FP) recall = float(TP) / (TP + FN) fmeasure = 2 * (precision * recall / (precision + recall)) test.append([precision, recall, fmeasure]) return test
def MenuPrincipal(): imprimir_menu() opcion = input("") Beep.Beep() while (opcion != '1' and opcion != '2' and opcion != '3'): print("==>Por Favor eliga opción 1 o 2<==") opcion = input("") Beep.Beep() Limpiar.Limpiar() if (opcion == '1'): Play.play() time.sleep(3) return True elif (opcion == '2'): Limpiar.Limpiar() Ranking.ImprimirRanking() input("presione enter para volver...") return True elif (opcion == '3'): despedir() return False
def testReadFile(self): rows = Ranking.read_tsv(TestData('qbs.tsv')) self.assertEqual(['1', 'Aaron Rodgers', 'GB', 'vs. KC', '1', '1', '1', '0'], rows[0]) self.assertEqual(['37','Jimmy Clausen','CHI','at SEA','34','34','34','0'], rows[36]) self.assertEqual(37, len(rows))
def Principi(): entrada = True while (entrada): print(" MENU") print("===============") print("1--> Crear usuari") print("2--> Iniciar Sessio") print("3--> Ranking") print("4--> Eliminar Usuari") print("5--> Sortir") opcio = (input("OPCIO --> ")) if (opcio == "1"): os.system('cls') OpcionsUsuari.crearUsuari(mycursor) elif (opcio == "2"): os.system('cls') IniciSessio.iniciarsessio(mycursor) elif (opcio == "3"): os.system('cls') Ranking.Ranking(mycursor) elif (opcio == "4"): os.system('cls') OpcionsUsuari.eliminarusuari(mycursor) elif (opcio == "5"): print("Adeu!") entrada = False else: os.system('cls') print("valor incorrecte")
def setupUi(self, Form): self.Rank = Ranking() Form.setObjectName(_fromUtf8("Form")) Form.resize(70, 20) p = self.palette() p.setColor(self.backgroundRole(), QtCore.Qt.darkRed) self.setPalette(p) font = QtGui.QFont() font.setFamily(_fromUtf8("MS UI Gothic")) font.setPointSize(10) font.setBold(True) font.setWeight(75) self.Layout = QtGui.QVBoxLayout(Form) self.Layout.setObjectName(_fromUtf8("verticalLayout")) self.texto = QtGui.QLabel(Form) self.texto.setFont(font) self.texto.setText('GAME OVER') self.Layout.addWidget(self.texto) self.puntos = QtGui.QLabel(Form) self.puntos.setFont(font) self.puntos.setText('SCORE: {}'.format('0')) self.Layout.addWidget(self.puntos) self.User = QtGui.QLineEdit(Form) self.User.setObjectName(_fromUtf8("plainTextEdit")) self.Layout.addWidget(self.User) self.buttonBox = QtGui.QDialogButtonBox(Form) self.buttonBox.setStandardButtons(QtGui.QDialogButtonBox.Ok) self.buttonBox.setObjectName(_fromUtf8("buttonBox")) self.Layout.addWidget(self.buttonBox) self.retranslateUi(Form) QtCore.QMetaObject.connectSlotsByName(Form) self.buttonBox.clicked.connect(self.IngresarNombre) shortcut = QtGui.QShortcut(QtGui.QKeySequence("Enter"), self, self.IngresarNombre) shortcut.setContext(QtCore.Qt.WidgetShortcut)
def do_POST(self): self.send_response(200) self.send_header('Content-type', 'text/html') content_length = int(self.headers.getheader('Content-Length')) body = self.rfile.read(content_length).split('\r\n') text = body[3] query = testCFCQueries.query() query.readFromString(text) rank = Ranking.ranking() rank.loadAll() scores = testCFCQueries.getRankScores(rank, query) relevantFiles = [] for i in range(min(20, len(scores))): if scores[i][1] == 0: break else: relevantFiles.append(scores[i][0]) self.end_headers() self.wfile.write('<div></h2>Your Query: ' + text + "</h2>") if not relevantFiles: self.wfile.write( '<h3>Sorry, there is no match for your query.</h3>') else: self.wfile.write('<h3>Search Results(At most 20):</h3>') for file in relevantFiles: self.wfile.write("<div>File ID: " + file) self.wfile.write("<li>") self.wfile.write(rank.IP.docText[file] + "</li></div><hr>") self.wfile.write('</div></body></html>')
def __init__(self, folder): self.corpus = TextMining.load_from_file(folder+"/tfidf") self.ranker = Ranking.load_from_file(folder+"/pagerank") self.text_folder = folder+"/text" self.pdf_folder = folder+"/pdf_pages" tfidf = self.corpus.TFIDF with concurrent.futures.ThreadPoolExecutor() as executor: tfidf = np.array(list(executor.map(lambda x : x/np.linalg.norm(x), tfidf))) self.corpus.TFIDF = tfidf
def guess_points(player_name, position): url = Ranking.create_standard_link(position) rankings = Ranking.read_tsv(Ranking.download_rankings(url)) rank = rankings.index(player_name) logging.info('{}\'s rest of season ranking is {}.'.format(player_name, rank+1)) db = PlayerDB() year_scores = [] calc = Calculator(read_scoring_file(get_resource('standard.json'))) for year in range(2009, 2015): year_scores.append(calc.sort_position(db.query_players_by_year(year), position)) avg_scores = average_lists(*year_scores) avg_score = avg_scores[rank] logging.info('On average (from 2009-2015) players that finished with the {}{} ' 'most points scored {} points in a year, or {}/game.' .format(rank+1, suffix(rank+1), avg_score, avg_score/16.0)) # TODO: What do we divide this number by? Not all players play 16 games return avg_score / 16.0
def fast_guess_points(scoring, player_name, position): averages = get_averages(scoring, position) ranking = Ranking.get_ranking(scoring, player_name, position) avg_score = averages[ranking] logging.info('Guessing expected points for {} ({}) with {} scoring'.format(player_name, position, scoring)) logging.info('Rest of season {} ranking: {}'.format(position, ranking+1)) logging.info('On average (from 2009-2015) players that finished with the {}{} ' 'most points scored {} points in a year, or {}/game.' .format(ranking+1, suffix(ranking+1), avg_score, avg_score/16.0)) return round(avg_score / 16.0, 2)
def __init__(self, folder): #Load file hasil preprocessing self.corpus = TextMining.load_from_file(folder+"/tfidf") self.ranker = Ranking.load_from_file(folder+"/pagerank") #simpan file raw txt dan pdf self.text_folder = folder+"/text" self.pdf_folder = folder+"/pdf_pages" #Normalisasi TFIDF tfidf = self.corpus.TFIDF with concurrent.futures.ThreadPoolExecutor() as executor: tfidf = np.array(list(executor.map(lambda x : x/np.linalg.norm(x), tfidf))) self.corpus.TFIDF = tfidf
def calculateSimilarItems(prefs,n=10): # Create a dictionary of items showing which other items they # are most similar to. result={} # Invert the preference matrix to be item-centric itemPrefs = GetRecommendation.transformPrefs(prefs) for item in itemPrefs: # Find the most similar items to this one scores=Ranking.topMatches(itemPrefs,item,n=n,similarity= sim_distance.sim_distance) result[item]=scores return result
def calculateSimilarItems(prefs, n=10): # Create a dictionary of items showing which other items they # are most similar to. result = {} # Invert the preference matrix to be item-centric itemPrefs = GetRecommendation.transformPrefs(prefs) for item in itemPrefs: # Find the most similar items to this one scores = Ranking.topMatches(itemPrefs, item, n=n, similarity=sim_distance.sim_distance) result[item] = scores return result
def IRTest(texts, ir, num_cluster, percentage): #Buat cluster menggunakan algoritma kmeans kmeans = KMeans(n_clusters=num_cluster).fit(ir.corpus.TFIDF) #gabung antara cluster dengan halaman label = list(zip(kmeans.labels_, range(len(texts)))) #vector test untuk menyimpan nilai precision, recall dan fmeasure test = [] #untuk setiap cluster for cluster in range(num_cluster): #ambil dokumen yang berada pada cluster label_doc = list(filter(lambda x : x[0] == cluster, label)) #ambil raw text dari dokumen dalam cluster label_text = [texts[label_doc[i][1]] for i in range(len(label_doc))] #ambil tfidf dokumen pada cluster label_tfidf = np.array([ir.corpus.TFIDF[label_doc[i][1]] for i in range(len(label_doc))]) #lakukan peringkasan dengan algoritma textrank summa = Ranking.TextRank(label_tfidf).summarize(label_text, percentage) #retrive doc dengan query summa start = time.time() retrieved = [doc[0] for doc in ir.query(summa, len(label_doc))] print("time=%f"%(time.time() - start)) #hitung confusion matrix dic_label = {page[1]:True for page in label_doc} dic_retrieved = {page:True for page in retrieved} TP = sum([1 if page in dic_label else 0 for page in retrieved]) FP = sum([1 if page not in dic_label else 0 for page in retrieved]) FN = sum([1 if page not in dic_retrieved else 0 for page in label_doc]) #hitung recall dan precision precision = float(TP) / (TP + FP) recall = float(TP) / (TP + FN) fmeasure = 2 * (precision * recall / (precision + recall)) test.append([precision, recall, fmeasure]) return test
def main(self): while not self.done: self.events_input() self.display_frame() self.run_logic() if self.choice == "Play": GameLoop.Game(self.screen).main() elif self.choice == "Tutorial": pass #Instruction.Instruction(self.screen).main() elif self.choice == "Ranking": Ranking.Ranking(self.screen).main() elif self.choice == "Options": pass elif self.choice == "Quit": pygame.quit() sys.exit()
import pygame import time import Ranking from maps import Map Ranking.SetUsername() pygame.init() pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=256) pygame.mixer.music.load('Audio/background_music.mp3') pygame.mixer.music.set_volume(0.1) pygame.mixer.music.play(-1) game_map = Map() while not game_map.windowClosed: pygame.time.Clock().tick(30) game_map.screen.fill((255, 255, 255)) if game_map.initialScreen: game_map.initalScreen() elif game_map.selectScreen: game_map.playerAndMapScreen() elif game_map.instructionsScreen: game_map.instructionScreen() elif game_map.inGame: game_map.blitBackgroundMap() game_map.player.animatePlayerSprite()
import TextMining import nltk import numpy as np import Ranking #matrix data untuk menyimpan dokumen data = [] #baca semua halaman dari folder deeplearning/text for i in range(1, 800): data.append( [open(str.format("deeplearning/text/page-%d.txt" % i), "r").read()]) #buat potter stemmer stemmer = nltk.stem.PorterStemmer() #Hitung TFIDF dari data data = TextMining.Dokumen_Cluster(data, stemmer=[np.vectorize(stemmer.stem)], stopword=[TextMining.english_stopwords], verbose=True) #simpan TFIDF ke file data.toFile("deeplearning/tfidf") #Hitung rank rank = Ranking.CosinePageRank(data.TFIDF) #simpan rank ke file rank.toFile("deeplearning/pagerank")
total_count = 0 total_correct = 0 average_points = [] discrete_points = [] middle_points = [] # for drawing a line at the 0.5 level x_values = [] labels = [ "Daily ratio of successful guesses", "Average ratio of successful guesses" ] starting_day = 20 for i in range(0, 100): day = Parser.getNextDay(fp) middle_points.append(0.5) if i > starting_day: correct, count = Ranking.predictOutcomesByProbability(day) total_correct = total_correct + correct total_count = total_count + count average_points.append(total_correct / total_count) discrete_points.append(correct / count) x_values.append(i) print(total_correct, "/", total_count, (total_correct / total_count)) Ranking.addEntry(day) # Ranking.printHmAwayProb() mpl.ylim([0.1, 0.9]) print(total_correct, "/", total_count, (total_correct / total_count)) mpl.plot(x_values, discrete_points) mpl.plot(x_values, average_points)
def _event_handler(event_type, slack_event): print(slack_event["event"]) msg = {} keywords ="" msg["color"] = "#3AA3E3" msg["text"] = "" msg["image_url"] = "None" if event_type == "app_mention": channel = slack_event["event"]["channel"] text = slack_event["event"]["text"] #text가 실제입력값 result = re.sub(r'<@\S+> ', '', text) # result = 받은 텍스트 title_list, title_url_list = crawl_movie_rank() # 영화 랭킹페이지 크롤링 호출 if "순위" in result: # 출력 선택 구문 msg["text"] = str(u'\n'.join(Ranking(title_list,title_url_list))) elif "ㅅㅇ" in result: # 출력 선택 구문 msg["text"] = str(u'\n'.join(Ranking(title_list, title_url_list))) elif "ㄹㅋ" in result: # 출력 선택 구문 msg["text"] = str(u'\n'.join(Ranking(title_list, title_url_list))) elif "ㅇㅈ" in result: msg["text"] = str(u'\n'.join(Release())) elif "개봉예정작" in result: msg["text"] = str(u'\n'.join(Release())) elif switching(result, title_list, title_url_list) == "정답": for i in range(10): # 타이틀 리스트 10개를 돌면서 텍스트와 비교해 주소를 url에 넘김, 영화제목이 없으면 url은 비어있음 if result == title_list[i]: title_URL = title_url_list[i] # 크롤링할 url 저장한 string break msg["image_url"] = img_link(title_URL) msg["text"] = str(u'\n'.join(info(title_URL))) # (영화제목과 주소4)개 elif "안녕" in result: msg["text"] = str(u"안녕하세요") # elif "출력실험" in result: # return elif "" in result: msg["text"] = str("실행 가능 명령어는 아래와 같습니다.\n순위\n개봉예정작\n영화제목(순위권 내)") # keywords = answer(text) sc.api_call( "chat.postMessage", channel=channel, text=keywords, attachments=json.dumps([msg]) ) msg["image_url"] = "None" return make_response("App mention message has been sent", 200, ) # ============= Event Type Not Found! ============= # # If the event_type does not have a handler message = "You have not added an event handler for the %s" % event_type # Return a helpful error message return make_response(message, 200, {"X-Slack-No-Retry": 1})
from RewardMatrix import * from Training import * from Live import * from MTM import * from Ranking import * from QMatrix import * from PerformanceMeasures import * import calendar import logging if __name__ == "__main__": logging.basicConfig(filename='out.log',level=logging.DEBUG) dbObject = DBUtils() rankingObject = Ranking() mtmObject = MTM() rewardMatrixObject = RewardMatrix() qMatrixObject = QMatrix() trainingObject = Training() liveObject = Live() reallocationObject = Reallocation() dbObject.dbConnect() #Calculates number of individuals in tradesheet table Number=dbObject.dbQuery("SELECT COUNT(DISTINCT(individual_id)),1 FROM "+gv.name_Tradesheet_Table) for num1,num2 in Number: MaxIndividuals=num1
self.params = json.loads(f.read()) except ValueError as e: print(e) self.save() f.close() def save(self): f = codecs.open(CONFIG_FILE, 'w', 'utf-8') f.write(json.dumps(self.params)) f.close() ######################### PARTE CONVERSACIÓN ################################### HELLO, BIEN, NAME = range(3) d_users = {} ranking = rank.Ranking("Ranking") ranking.ReadTXT() print(ranking.printRanking()) to_type = [] ################################# DIÁLOGOS ##################################### import traceback try: def text(bot, update): text = update.message.text text_out = elimina_tildes(text) id = update.message.chat.id myuser = d_users[id] print(text)
for ageKeyword in keyword: print(ageKeyword) while True: # query variables query = [] query_tf = [] query_weight = [] query_text1 = f.readline().rstrip('\n') print(query_text1) if not query_text1: break query.append(PreprocessComment(query_text1)) query_tf = TF(indexing_list, query, 'query') query_weight = Weighting(query_tf, idf_list) query_weight = Normalize(query_weight) score = Scoring(weighting_list, query_weight) rank = Ranking(score) print(rank) print("") count += 1 for r in rank: if (str(list(r.keys())[0]) == '10대'): result += 1 print("전체 댓글 : %d " % count) print("결과 : %d " % result) print("정확도 : %f" % (result / count))
def testDownloadRankings(self, urllib_mock): urllib_mock.return_value.read.return_value = TestData('rbs.tsv') link = Ranking.create_ppr_link('RB') rankings = Ranking.download_rankings(link).splitlines() self.assertEqual('FantasyPros.com', rankings[1].strip()) self.assertEqual('Week 3 - RB Rankings', rankings[2].strip())
def testReadRankings(self): rankings = Ranking.read_rankings(TestData('qbs.tsv')) self.assertEqual('aaron rodgers', rankings[0]) self.assertEqual('jimmy clausen', rankings[36]) self.assertEqual(37, len(rankings))
sg.Column(column1, key='-C1-'), sg.VerticalSeparator(), sg.Column(column2, key='-C2-') ]] window1 = sg.Window('ScrabbleAr ', layout) while True: event, value = window1.read() if event == None: break if event == '-ADVANCED_CONFIG-': Config.main(easy_config, medium_config, hard_config) if event == '-README-': ConoceMas.main() if event == '-RANKING-': Ranking.main() if event == '-SIGN_UP-': Registro.main() window1['-SIGN_UP-'].Update(disabled=True) if event == '-LOGIN-': usuario = value['nick'] password = value['password'] lista_jugadores = ListaJugadores() a = Database.abro_base() try: if a != None: lista_jugadores_2 = Database.abro_base() usuario_valido = False for jugador in lista_jugadores_2.get_jugadores(): if jugador.get_nick() == usuario and jugador.get_password(
def main(): while 1: print('=' * 20) print('请输入指令:') cmd = input() print('=' * 20) # ------------------- if cmd == '说明': # --------------- print( '程序说明\n1.输入"search"进入抓取分支:复制进关键词(以"#"结束,回车分隔)\n2.输入"query"进入多关键词搜索分支\n3.title/domin排名全查询(' '以"title:"/"domain:"开始)\n4.输入"微信登录",扫码后发送"查询结果"给文件传输助手\n5.') # ------------------- if 'search' in cmd: # ---多关键词分支 print('- 多关键词抓取分支 -') print('- 以#结束 -') keywords = [] # 多行输入关键词 while 1: k = input() if k == '#': print('即将抓取"{k}"...请确认(y/n)'.format(k=keywords)) if input() == 'y': print('- 开始抓取 -') Ranking.scrape_multi(keywords) print('- 抓取完毕 -') break else: break else: keywords.append(k) if cmd == 'query': print('请选择:1.标题匹配/2.域名匹配') choose = input() if choose == '1': print('- 多关键词标题排名匹配分支 -') print('- 以#结束 -') match_title = [] while 1: k = input() if k == '#': print('即将匹配"{k}"...请确认(y/n)'.format(k=match_title)) if input() == 'y': print('- 开始匹配 -') frame = pd.read_excel('./data/keyword-multi.xlsx') match_title_function(frame, match_title) print('- 匹配完毕 -') break else: break else: match_title.append(k) # ------------------------------- if choose == '2': print('- 多关键词域名排名匹配分支 -') print('- 以#结束 -') match_domain = [] while 1: k = input() if k == '#': print('即将匹配"{k}"...请确认(y/n)'.format(k=match_domain)) if input() == 'y': print('- 开始匹配 -') frame = pd.read_excel('./data/keyword-multi.xlsx') match_domain_function(frame, match_domain) print('- 匹配完毕 -') break else: break else: match_domain.append(k) # --------------- if 'title:' in cmd: key = cmd.replace('title:', '').strip() try: frame = pd.read_excel('./data/keyword-multi.xlsx') Search_Keyword_Multi(frame, key) except Exception: print('- 文件不存在 -') # ------------------------ if 'domain:' in cmd: key = cmd.replace('domain:', '').strip() try: frame = pd.read_excel('./data/keyword-multi.xlsx') Search_Domain_Multi(frame, key) except Exception: print('- 文件不存在 -') if cmd == '微信登录': itchat.auto_login(enableCmdQR=2) itchat.run() if cmd == 'exit': break
from datetime import timedelta, datetime from Reallocation import * from RewardMatrix import * from Training import * from Live import * from MTM import * from Ranking import * from QMatrix import * from PerformanceMeasures import * from Plots import * import calendar if __name__ == "__main__": dbObject = DBUtils() rankingObject = Ranking() mtmObject = MTM() rewardMatrixObject = RewardMatrix() qMatrixObject = QMatrix() trainingObject = Training() liveObject = Live() reallocationObject = Reallocation() plotObject = Plots() performanceObject = PerformanceMeasures() dbObject.dbConnect() ''' dbObject.dbQuery("DELETE FROM asset_allocation_table") dbObject.dbQuery("DELETE FROM asset_daily_allocation_table") dbObject.dbQuery("DELETE FROM mtm_table")
janela.draw_text((":"), 200, 20, size=26, color=(255, 0, 0), font_name="Purisa", bold=True, italic=False) janela.draw_text(str(milisegundos), 210, 20, size=26, color=(255, 0, 0), font_name="Purisa", bold=True, italic=False) janela.draw_text(("Score: "), 1100, 20, size=26, color=(255, 0, 0), font_name="Purisa", bold = True, italic = False) janela.draw_text((str(x)), 1200, 20, size=26, color=(255, 0, 0), font_name="Purisa", bold=True, italic=False) if acabou: break principal.draw() janela.update() global primeiraVez if primeiraVez: primeiraVez = False prepara(janela) while(True): opcao = menu.menu(janela) if opcao == 0: game(janela) Ranking.SalvaRanking(x, janela) elif opcao == 1: Ranking.ExibeRanking(janela) janela.update()
def ranking(self): pilas.cambiar_escena(Ranking.Ranking())
def init(l): gv.lock = l if __name__ == "__main__": logging.basicConfig(filename=gv.logFileName, level=logging.INFO, format='%(asctime)s %(message)s') l = Lock() pool = Pool(gv.maxProcesses, initializer=init, initargs=(l, )) dbObject = DBUtils() rankingObject = Ranking() mtmObject = MTM() rewardMatrixObject = RewardMatrix() qMatrixObject = QMatrix() trainingObject = Training() liveObject = Live() reallocationObject = Reallocation() plotObject = Plots() performanceDrawdownObject = PerformanceDrawdown() performanceObject = PerformanceMeasures() dbObject.dbConnect() dbObject.dbQuery("DELETE FROM asset_allocation_table") dbObject.dbQuery("DELETE FROM asset_daily_allocation_table") dbObject.dbQuery("DELETE FROM mtm_table")