def get_answers(self): soup = self.soup if soup.find("div", class_="zm-invite-pager") is not None: total_pages = soup.find("div", class_="zm-invite-pager").find_all("span") total_pages = int(total_pages[len(total_pages) - 2].string) for i in range(1, total_pages): url = self.url + "?page=%d" % i r = requests.get(url) soup = BeautifulSoup(r.content) tags = soup.find("div", id="zh-list-answer-wrap").find_all( "div", class_="zm-item") for tag in tags: question_part = tag.find("h2").find("a")["href"] answer_part = tag.find( "div", class_="zm-item-answer ")["data-atoken"] answer_url = "http://www.zhihu.com" + question_part + "/answer/" + answer_part from Answer import Answer yield Answer(answer_url) else: tags = soup.find("div", id="zh-list-answer-wrap").find_all( "div", class_="zm-item") for tag in tags: question_part = tag.find("h2").find("a")["href"] answer_part = tag.find("div", class_="zm-item-answer ")["data-atoken"] answer_url = "http://www.zhihu.com" + question_part + "/answer/" + answer_part from Answer import Answer yield Answer(answer_url)
def operate(self): self.show_item_info() while True: op = raw_input("Question Answer Item$ ") if op == "voteup": self.vote_up_answer() elif op == "votedown": self.vote_down_answer() elif op == "votecancle": self.vote_cancle_answer() elif op == "answer": from Answer import Answer answer = Answer(zhihu + self.get_answer_link()) if answer.operate(): return True elif op == "author": author_link = self.get_author_link() if author_link: user = User(zhihu + self.get_author_link()) if user.operate(): return True else: print termcolor.colored("回答者为匿名用户", "red") elif op == "pwd": self.show_item_info() elif op == "help": self.help() elif op == "break": break elif op == "clear": clear() elif op == "quit": return True else: error()
def operate(self): self.show_item_info() while True: op = raw_input("{}\'s Answer Item$ ".format(self.username)) if op == "voteup": self.vote_up() elif op == "votecancle": self.vote_cancle() elif op == "votedown": self.vote_down() elif op == "answer": answer_link = self.get_answer_link() from Answer import Answer answer = Answer(zhihu + answer_link) if answer.operate(): return True elif op == "question": from Question import Question question = Question(zhihu + self.get_question_link()) if question.operate(): return True elif op == "pwd": self.show_item_info() elif op == "quit": return True elif op == "help": self.help() elif op == "clear": clear() elif op == "break": break else: error()
def operate(self): self.show_item_info() while True: op = raw_input("{}\'s Answer Item$ ".format(self.username)) if op == "voteup": self.vote_up() elif op =="votecancle": self.vote_cancle() elif op == "votedown": self.vote_down() elif op == "answer": answer_link = self.get_answer_link() from Answer import Answer answer = Answer(zhihu + answer_link) if answer.operate(): return True elif op == "question": from Question import Question question = Question(zhihu + self.get_question_link()) if question.operate(): return True elif op == "pwd": self.show_item_info() elif op == "quit": return True elif op == "help": self.help() elif op == "clear": clear() elif op == "break": break else: error()
def pick_answer(self, choices=None): if choices is None: arr = MastermindConstants.starting_recommendation input_var = "" for i in range(0, 4): input_var += random.choice(arr) choices = input_var self.Answer = Answer(choices)
def main(dbfile, cmd): if (not os.path.exists(dbfile) or not dbfile.endswith(".db")): raise FileExistsError conn = sqlite3.connect(dbfile) gAnswer = Answer(conn) gAnswer.Loads() import sys if cmd: CmdShell(gAnswer).onecmd(cmd) else: CmdShell(gAnswer).cmdloop()
def getAnswer(self, query): intent = self.intentService.getIntent(query) print("Intent before if else:", intent.name) if intent.name == "Greeting": print("Intent:", intent.name) text = random.choice(self.GREETINGS) return Answer(0, text, text, "Greeting") elif intent.name == "InformationRetrieval": print("Intent:", intent.name) answer = self.informationRetrievalService.getTopNAnswers(query, 1) return answer[0] elif intent.name == "Farewell": print("Intent:", intent.name) text = random.choice(self.FAREWELLS) return Answer(0, text, text, "Farewell")
def process_answer(self, passage, question): q = question.text p = passage.text searched_entity = self._question_classification(q) try: ner_algorithm = MyConfig.get("answer_extraction", "ner") except MyConfigException as e: ner_algorithm = "stanford" logger = logging.getLogger("qa_logger") logger.warning(str(e)) if ner_algorithm == "nltk": entities = self._nltk_ner(p, searched_entity, question) else: entities = self._stanford_ner(p, searched_entity, question) entities = self._filter_entities(entities, q) exact, window, score = self._entity_ranking(entities) answer = Answer(passage, question, window, exact, score) return answer
def fetch(self): try: with open(f'{self.path}{self.file}', 'r') as file: dictionaries = json.load(file) completed_forms = [] for item in dictionaries: form = Form(item['form']['name']) for question in item['form']['questions']: if question['type'] == 'TEXT': form.questions.append( TextQuestion(question['question'])) elif question['type'] == 'NUMBER': form.questions.append( NumberQuestion(question['question'])) elif question['type'] == 'DROPDOWN': form.questions.append( DropdownQuestion(question['question'], question['options'])) elif question['type'] == 'DATE': form.questions.append( DateQuestion(question['question'])) completed_form = CompletedForm(form) answers = [] for answer in item['answers']: answers.append(Answer(answer['answer'])) completed_form.answers = answers completed_forms.append(completed_form) self.completed_forms = completed_forms return completed_forms except Exception as error: pass
def get_answers(self): soup = self.soup answer_tags = soup.find_all("div", class_="zm-item-answer") from Answer import Answer for answer_tag in answer_tags: answer_url = self.url + "/answer/" + answer_tag["data-atoken"] yield Answer(answer_url)
def on_validate(self): # Get the user input answerText = self.answerText_lineEdit.text() commentText = self.comment_lineEdit.text() # Verify it if answerText is not None and answerText is not "": if commentText == "": commentText = None changes = { 'academics' : self.academicsSlider.value(), 'social' : self.socialSlider.value(), 'finances' : self.financesSlider.value(), 'health' : self.healthSlider.value() } # Everything is ok, emit completed signal and dismiss the dialog answer = Answer(answerText, changes, commentText, self.suiteCombo.currentText()) self.completed.emit(answer) self.dialogRef.accept() else: messageBox = QMessageBox() messageBox.setText('La réponse ne doit pas être vide!') messageBox.exec()
def quiz_decider(self, mesutozil, poll, Ans_Key): attend = False islemsirasi = False # Bu isim degissin for x in mesutozil.matched_student_list: for index, row in poll.iterrows(): if (poll.iloc[index, 4] == 'Are you attending this lecture?'): islemsirasi = True if (poll.iloc[index, 1] == x.zoom_account.username): attend = True break else: attend = False else: if (poll.iloc[index, 1] == x.zoom_account.username): quiz = Poll_Quiz() for k in poll.iloc[index, lambda poll: [4, 6, 8, 10, 12, 14, 16, 18, 20, 22]]: # df.iloc[lambda x: x.index % 2 == 0] if (k != None): temp_question = Question(k) quiz.add_question(temp_question) for l in poll.iloc[index, lambda poll: [5, 7, 9, 11, 13, 15, 17, 19, 21, 23]]: if (l != None): temp_answer = Answer(l) quiz.add_student_answer(temp_answer) if (quiz.question_list[1].question_text == Ans_Key.q_list[1].question_text): quiz.give_name_to_poll(Ans_Key.poll_name) else: quiz.give_name_to_poll('Couldnt find') x.poll_adder(quiz) if (islemsirasi): attendance_poll = Poll_Attendance(x, attend)
def main(self): self.idf = {} self.paras = re.split('\s{4,}', self.text) N = len(self.paras) ni = {} tf = [] self.qv = processData(self).queryVector(self.question) for para in self.paras: pd = processData(self) temp = pd.findTfVector(para) tf.append(temp) for word in temp.keys(): if not word in ni: ni[word] = 0 ni[word] += 1 for word in ni: self.idf[word] = math.log((N + 1) / ni[word]) sim = [] for tfForDoc in tf: sim.append(processData(self).findSim(self.qv, tfForDoc, self.idf)) self.sim = sorted(enumerate(sim), key=operator.itemgetter(1), reverse=True) self.question_type = Question().classifyQues(self.question) self.answer = Answer().getAnswer(self) return self.answer
def __init__(self): self.questions = [] root = ET.parse('TruthOrLieQuiz.xml').getroot() for type_tag in root.findall('question'): qId = type_tag.get('id') text = type_tag.get('text') info = type_tag.get('info') qAnswers = type_tag.findall('answer') answers = [0, 0, 0, 0] answers[0] = Answer(qAnswers[0].get('id'), qAnswers[0].get('text'), qAnswers[0].get('correct')) answers[1] = Answer(qAnswers[1].get('id'), qAnswers[1].get('text'), qAnswers[1].get('correct')) answers[2] = Answer('', '', '') answers[3] = Answer('', '', '') self.questions.append(QuizQuestion(qId, text, info, answers))
def test_answer_unknownVm(self): """ Verify that we raise an appropriate exception if the operation is invoked with an unknown vm name. """ self.failUnlessRaises(pyVmomi.vim.fault.NotFound, Answer().DoIt, self.host, 'unknownVm')
def getTopNAnswers(self, query, n): queryVector = self.model.infer_vector(prepInput(query)) sims = self.model.docvecs.most_similar([queryVector], topn=len(self.model.docvecs)) results = [] for item in sims[: n]: text = self.document.docList[item[0]] topic = self.document.allTopics[item[0]].strip() results.append(Answer(2, text, "html", topic)) return results
def GetQuestionAnswers(self): answersXml = self.__root.findall('answers/answer') answers = [] for answerXml in answersXml: text = answerXml.text iscorrect = answerXml.attrib.get('iscorrect') == 'true' answer = Answer(text, iscorrect) answers.append(answer) return answers
def __ask_question(self, question): raw_answer = self.answerer({ 'question': question, 'context': self.context }) raw_answer['question'] = question answer = Answer(raw_answer) return answer
def get_answers(self): answers_num = self.get_answer_num() if answers_num == 0: return else: for i in xrange((answers_num - 1) / 20 + 1): answer_url = self.url + "/answers?page=" + str(i + 1) r = requests.get(answer_url) soup = BeautifulSoup(r.content) from Answer import Answer for answer_tag in soup.find_all("a", class_="question_link"): answer_url = 'http://www.zhihu.com' + answer_tag["href"] #if not answerBloom.is_element_exist(answer_url): # answerBloom.insert_element(answer_url) yield Answer(answer_url)
def get_answers(search): answers = [] url = f'https://www.googleapis.com/customsearch/v1?key={API_KEY}&cx={CSE}&cr=countryBR&gl=br&lr=lang_pt&q={search}' data = requests.get(url).json() search_items = data.get('items') for i, search_item in enumerate(search_items, start=1): print(search_item) answer = Answer(search_item.get('title'), search_item.get('link'), search_item.get('displayLink'), search_item.get('snippet')) answers.append(answer) return answers
def getTopNAnswers(self, query, n): htmlOutput = [] answers = [] indeces = self.get_most_similar_documents(query, n) headlineIndeces = self.compareToTopics(query, n) for i in range(len(indeces)): a = indeces[i] b = headlineIndeces[i] res = a if a > b else b text = self.document.rawDocList[b] resultNodes = self.document.nodeList[b] topic = resultNodes[0].topic.strip() for node in resultNodes: htmlOutput.append(str(node.data)) answers.append(Answer(2, text, "".join(htmlOutput), topic)) return answers
def __init__(self, file): cor_answer = pd.read_csv(file, encoding="utf-8") self.poll_name = cor_answer.columns[0] self.q_list = [] self.correct_answer_list = [] i = 0 for index in cor_answer.iterrows(): ans = Answer(cor_answer.iloc[i, 0]) self.add_correct_answer(ans) i += 1 x = 0 for index in cor_answer.iterrows(): question = Question(cor_answer.iloc[x].name) self.add_question(question) x += 1
def getTopNAnswers(self, query, n): """ :param query: :param n: :return: """ answers = [] cosSimValues = [] htmlOutput = [] textOutput = [] queryVec = getVectorFromQuery(query, self.uniqueTerms) lsiQueryVec = np.linalg.inv(self.Sk).dot(np.transpose( self.uk)).dot(queryVec) for col in self.vhk.T: cosSimValues.append(1. - spatial.distance.cosine(lsiQueryVec, col)) headlineCosSimValues = self._compareQueryToTopics(query) a = np.array(headlineCosSimValues) b = np.array(cosSimValues) normalizedA = [] normalizedB = [] combinedValues = [] for i in range(len(cosSimValues)): normalizedA.append((a[i] - np.min(a)) / (np.max(a) - np.min(a))) normalizedB.append((b[i] - np.min(b)) / (np.max(b) - np.min(b))) topNhighestScoresIndeces = np.argsort(np.array(cosSimValues))[-n:] topNhighestHeadlineScoresIndeces = np.argsort( np.array(headlineCosSimValues))[-n:] for i in range(len(topNhighestScoresIndeces)): a = topNhighestScoresIndeces[i] b = topNhighestHeadlineScoresIndeces[i] A = normalizedA[a] B = normalizedB[b] c = cosSimValues[a] d = headlineCosSimValues[b] res = a if A > B else b topResultNodes = self.nodes[res] for node in topResultNodes: htmlOutput.append(str(node.data)) textOutput.append(node.data.getText()) topResultTopicHeadline = topResultNodes[0].topic answers.append( Answer(2, textOutput, "".join(htmlOutput), topResultTopicHeadline)) return answers
def test_answer_Question(self): try: ## Make rawInputStub act as if the user entered '0' in ## response to the question. self.rawInputStub.answer = '0' def _Answer(questionId, choice): """ This function is a replacement for the Vm.Answer method that does nothing except check that it has been called with expected args. """ self.assertEqual(questionId, self.vmQuestion.runtime.question.id, '_Answer got questionId == "%s"' % questionId + '; expected "%s"' % self.vmQuestion.runtime.question.id) self.assertEqual(choice, self.rawInputStub.answer, '_Answer got choice == "%s"' % choice + '; expected "%s"' % self.rawInputStub.answer) ## Redefine the Answer method of the Vm stub so that it ## invokes our _Answer function. self.vmQuestion.Answer = _Answer ## Capture what the SUT is writing to stdout so that we can ## verify it later. sys.stdout = FileWriteCapture(sys.stderr).StartCapture() result = Answer().DoIt(self.host, self.vmQuestion.name) self.assertTrue(result is None, 'result == "%s"; result != None' % result) finally: ## Instead of checking what was written to sys.stdout ## verbatim (probably brittle), we check that various strings ## were all written to sys.stdout for aStr in ('Question (id = someQuestionId)', self.vmQuestion.runtime.question.text, 'Select choice. Press enter for default', 'selected %s' % self.rawInputStub.answer): self.assertTrue(aStr in sys.stdout.getvalue(), 'Did not find "%s" in stdout' % aStr) ## Revert to the normal sys.stdout sys.stdout = sys.stdout.EndCapture()
def iter_game_ai(): """" Plays every single game (i.e. for each hidden answer possible) """ i = 0 wins = 0 possibles = Answer.possible_answers() game_ai = GameAI() g = Game() for p in possibles: i += 1 game_ai.reset() g.reset() status = play_game_ai(p, game_ai, g) if status == "Won": wins += 1 print("{} / {} wins".format(wins, i))
def getTopNAnswers(self, query, n): """ :param query: The query string :param n: The number of the top N answers to retrieve :return: List of Answer objects """ answers = [] cosSimValues = [] htmlOutput = [] textOutput = [] queryVec = getVectorFromQuery(query, self.uniqueTerms) for col in self.termDocMatrix.T: cosSimValues.append(1. - scipy.spatial.distance.cosine(queryVec, col)) headlineCosSimValues = self._getTopicSims(query) topNhighestScoresIndeces = np.argsort(np.array(cosSimValues))[-n:] topNhighestheadlineScoresIndeces = np.argsort( np.array(headlineCosSimValues))[-n:] normalizedA = [] normalizedB = [] a = cosSimValues b = headlineCosSimValues for i in range(len(cosSimValues)): normalizedA.append((a[i] - np.min(a)) / (np.max(a) - np.min(a))) normalizedB.append((b[i] - np.min(b)) / (np.max(b) - np.min(b))) for i in range(len(topNhighestScoresIndeces)): a = topNhighestScoresIndeces[i] b = topNhighestheadlineScoresIndeces[i] A = cosSimValues[a] B = headlineCosSimValues[b] normA = normalizedA[a] normB = normalizedB[b] res = a if normA > normB else b topResultNodes = self.nodes[res] for node in topResultNodes: htmlOutput.append(str(node.data)) textOutput.append(node.data.getText()) topResultTopicHeadline = topResultNodes[0].topic answers.append( Answer(2, textOutput, "".join(htmlOutput), topResultTopicHeadline)) return answers
def test_answer_noQuestion(self): """ When the `answer` operation is invoked on a vm with no question pending, then we simply print an error message on stderr. """ try: ## Capture what the SUT is writing to stderr so that we can ## verify it later. sys.stderr = FileWriteCapture(sys.stderr).StartCapture() result = Answer().DoIt(self.host, self.vmNoQuestion.name) expectOnStderr = 'No questions pending.\n' self.assertEqual(sys.stderr.getvalue(), expectOnStderr, 'Did not see "%s" on stderr' % expectOnStderr.replace('\n', '\\n')) self.assertTrue(result is None, 'result == "%s"; result != None' % result) finally: ## Revert to the normal sys.stderr sys.stderr = sys.stderr.EndCapture()
def write_answers(self, answer_list, empty, q): id_q = q.id_q (run_tag, _) = Answer.get_run_tag() folder = os.path.join("..", "res") if not os.path.isdir(folder) and os.path.exists(folder): logger = logging.getLogger("qa_logger") logger.error("answers folder cannot be created") sys.exit() if not os.path.exists(folder): os.mkdir(folder) f = open(os.path.join(folder, self.date + ".txt"), "a") if answer_list == []: if empty: # If there are no documents related to the query, # then there is no answer with maximum probability. f.write(id_q + " " + run_tag + " 1 1000 NIL\n") else: # If there are no good answer, # then we return NIL with score 0. f.write(id_q + " " + run_tag + " 1 0 NIL\n") return position = 1 for answer in answer_list: f.write(str(answer).format(position) + "\n") position += 1 if len(answer_list) < 3: # If the are less than 3 good answers, # then we return NIL with score 0 in the next position f.write(id_q + " " + run_tag + " " + str(position) + " 0 NIL\n") f.close()
def complete_form(self): self.show_forms() if len(self.form_service.fetch()) > 0: print('Opcion: ', end='') opt = int(input()) form = self.form_service.forms[opt - 1] print(f'Selecionaste: {form.name}') completed_form = CompletedForm(form) answers = [] for question in form.questions: print(question.question) if question.type == 'DATE': print('Formato: %Y-%m-%d') if hasattr(question, 'options'): [print(f'[{num}] {opt} ', end=' ') for num, opt in enumerate(question.options)] print() answer = input() while not question.validate(answer): print('[ERROR] No cumple con el formato,\nIntenta de nuevo') answer = input() answers.append(Answer(answer)) completed_form.answers = answers self.completed_form_service.completed_forms.append(completed_form) self.completed_form_service.store()
def getTopNAnswers(self, query, n): # prepQuery = query.lower().split() prepQuery = prepInput(query) distances = [] answers = [] htmlOutput = [] textOutput = [] for doc in self.docs: # distances.append(self.model.wmdistance(prepQuery, doc)) distances.append(self.word2Vec.wv.wmdistance(prepQuery, doc)) npDistances = np.array(distances) npHeadlineDistances = self._compareToTopics(query) a = npDistances b = npHeadlineDistances normalizedA = [] normalizedB = [] for i in range(len(a)): normalizedA.append((a[i] - np.min(a)) / (np.max(a) - np.min(a))) normalizedB.append((b[i] - np.min(b)) / (np.max(b) - np.min(b))) resultsIndeces = np.argsort(npDistances)[:n] resultsHeadlineIndeces = np.argsort(npHeadlineDistances)[:n] for i in range(len(resultsIndeces)): a = resultsIndeces[i] b = resultsHeadlineIndeces[i] A = normalizedA[a] B = normalizedB[b] res = a if A < B else b topResultNodes = self.nodes[res] for node in topResultNodes: htmlOutput.append(str(node.data)) textOutput.append(node.data.getText()) topResultTopicHeadline = topResultNodes[0].topic answers.append( Answer(2, textOutput, "".join(htmlOutput), topResultTopicHeadline)) return answers
def main(): #输入文件绝对路径,arg1,arg2为要查重的文件,arg3为答案文件 parser = argparse.ArgumentParser(description="小学四则运算自动生成器") parser.add_argument('-n', '-na', type=str, help='控制生成题目的个数') parser.add_argument('-r', '-ra', type=str, help='题目中数值(自然数、真分数和真分数分母)的范围') parser.add_argument('-e', '-ea', type=str, default=" ", help='题目文件') parser.add_argument('-a', '-aa', type=str, default=" ", help='答案文件') args = parser.parse_args() n = int(args.n) r = int(args.r) e = args.e e = e.strip() a = args.a a = a.strip() product = Product(r, n) questions = product.problemArray #存储生成的表达式,存进 : “Exercises.txt” answer = Answer() answer.expression_result(questions) #生成题目的答案、 if os.path.exists(e) and os.path.exists(a): print("核对答案") answer.check_answer(e, a)
def operate(self): d = self.get_item_info() ftype = self.get_feed_type() print "\n".join(i for i in d[1] if i) + "\n" while True: global flag op = raw_input("Time Line Item$ ") if op == "answer": if ftype.startswith("ANSWER"): #print d[2][1] from Answer import Answer answer = Answer(d[2][1]) #print answer.get_full_answer() if answer.operate(): flag = False return True else: error() elif op == "question": if ftype.startswith("ANSWER") or ftype.startswith("QUESTION"): #print d[2][0] from Question import Question question = Question(d[2][0]) if question.operate(): flag = False return True else: error() elif op == "author": if d[2][2]: #print d[2][2] from User import User user = User(d[2][2], self._xsrf) if user.operate(): flag = False return True else: error() elif op == "zhuanlan": if ftype.find("ARTICLE") != -1: url = self.get_zhuanlan_link() from Zhuanlan import Zhuanlan zhuanlan = Zhuanlan(url) if zhuanlan.operate(): flag = False return True else: error() elif op == "pwd": print "\n".join(i for i in d[1] if i) + "\n" elif op == "help": self.help() elif op == "break": break elif op == "clear": clear() elif op == "quit": flag = False return True else: error()