【问题标题】:Search for the most similar string in python在python中搜索最相似的字符串
【发布时间】:2017-12-13 15:43:50
【问题描述】:

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

【问题讨论】:

  • idownvotedbecau.se/noattempt(笑话:你看瑞克和莫蒂,你的智商应该足够解决这个问题)
  • 添加一些代码,向我们展示您的工作,然后我们将帮助/指导您解决问题。
  • @byxor 你所要做的就是给我一个算法的名称,我第一次使用stackoverflow时不需要粗鲁,如果我会继续使用reddit,它似乎有毒
  • @IMCoins 谢谢我已经成功了 我只是想找到一些好的搜索算法
  • @Obsession 抱歉,您是这样看的。我给了你一个链接,指出为什么人们对你的问题投了反对票(以及如何改进它),然后试图用一些你能理解的幽默来减轻情绪。以后我会避免 Rick & Morty 的笑话。

标签: python search chatbot


【解决方案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()

【讨论】:

    【解决方案2】:

    您可以尝试的最简单的事情是使用一些字符串相似性包,例如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
    

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

    【讨论】:

    • 感谢您的回答我忘记了这篇文章我最终使用了序列匹配器和 Levenshtein
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2014-01-25
    • 2016-04-21
    • 1970-01-01
    • 2015-08-17
    • 1970-01-01
    相关资源
    最近更新 更多