在python中搜索最相似的字符串

时间:2017-12-13 15:43:51

标签: python search chatbot

我在python中为一个学校项目做了一个聊天机器人,它很简单:我问一个问题,它会搜索一个包含所有问题和答案的txt文件,然后它给出并回答。 我想要做的是知道如何在数据库中搜索最相似的问题。

2 个答案:

答案 0 :(得分:1)

好吧,我忘记了我发布了这个,但是如果有人想使用它我就制作了代码和它的工作,我使用了SequenceMatcher和Levenshtein算法。

def startChatBot():
cls()
ExitFlag = 0
while (ExitFlag != 1):
    print('Write Exit to return to menu!!')
    FoundFlag = 0        
    Q = input("What is your question? \n")
    if (Q=='Exit'):
        ExitFlag=1
        main()
    elif (Q== 'Que horas são?'):
        print(datetime.datetime.now())
    else:
        bestRatio = 0
        BestDist = 40000
        #SequenceMatcher
        for item in database:
            if SequenceMatcher(None, item, Q).ratio()>AcceptanceRatio and SequenceMatcher(None, item, Q).ratio()>bestRatio:
                    squenceactual = SequenceMatcher(None, item, Q).ratio()
                    bestRatio = squenceactual
                    print('SquenceMatcher Found a better answer in the database with ratio of', bestRatio)
                    S = database.index(item)           
                    print(database[S+1])
                    FoundFlag = 1
        #Levenshtein            
        for item in database:
            actualDistance  = distance(Q, item)
            if (actualDistance < BestDist):
                BestDist = actualDistance
                Solution = database.index(item)
                print('Levenshtein found a better answer in the database with distance of', BestDist)
                FoundFlag = 1
        print(database[Solution+1])


        if FoundFlag == 0:
            print('Answer not found!\n')
            print('Can you add an answer?\n')
            k = input('Y for yes N for no\n')
            if k== 'Y' or k=='y':
                 correct = input('what is the correct answer? \n')
                 with open("BasedeDados.txt", "a") as file:
                      file.write('#')
                      file.write(Q)
                      file.write('#')
                      file.write(correct)
                 #close and reopen database                 
                 openFile()

        elif FoundFlag == 1:
            h = input('Was this the correct answer? Y-Yes N-No \n')
            if h == 'n' or h =='N':
               correct = input('what is the correct answer? \n')
               with open("BasedeDados.txt", "a") as file:
                     file.write('#')
                     file.write(Q)
                     file.write('#')
                     file.write(correct)
               #reopen datababse
               openFile()

答案 1 :(得分:0)

您可以尝试的最简单的事情是使用一些字符串相似性包,如fuzzywuzzy。它使用difflib,它是Python的标准库。

以下是您的用例的示例代码:

from fuzzywuzzy import fuzz
from fuzzywuzzy import process

query = 'user query'
options = [list of all questions in your file]
result = process.extractOne(query, options)
# result will contain best matching option and it's confidence score

同样,有很多更好的方法可以做到这一点,但我认为这是最简单的。