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

问题描述 投票:-5回答:2

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

python search chatbot
2个回答
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()

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

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

© www.soinside.com 2019 - 2024. All rights reserved.