import json def jaccard_similarity(userQuestion, questionBank): s1 = set(userQuestion) s2 = set(questionBank) return float(len(s1.intersection(s2)) / len(s1.union(s2))) def most_likely(userQuestion): likelihoodScore = [] fileObject = open("faq.json", "r") jsonContent = fileObject.read() aList = json.loads(jsonContent) for json_object in aList: likelihoodScore.append(jaccard_similarity(userQuestion, json_object['question'])) #print(likelihoodScore) mostLikelyIndex = likelihoodScore.index(max(likelihoodScore)) mostLikely = aList[mostLikelyIndex] return mostLikely def main(): print("Hello, I am a question answering bot.\n") userQuestion = '' while True: userQuestion = input('Please enter a question, and press the ENTER key: \n').strip() if userQuestion: likelyQuestion = most_likely(userQuestion) print ("I think that you asked " + "'" + (likelyQuestion['question']) + "'" + " and conclude that the answer is " + "'" + (likelyQuestion['answer']) + "'.\n") # Open the file in append & read mode ('a+') with open("asked_questions_log.txt", "a+") as file_object: file_object.seek(0) # Move read cursor to the start of file. data = file_object.read(100) if len(data) > 0 : # Append text at the end of file file_object.write("\n") file_object.write(userQuestion) else : print ("Goodbye!") exit() if __name__ == "__main__": main()