How do Markov Chain Chatbots work?

前端 未结 3 506
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 17:44

I was thinking of creating a chatbot using something like markov chains, but I\'m not entirely sure how to get it to work. From what I understand, you create a table from data w

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-29 18:08

    The bot chooses a random word from your input and generates a response by choosing another random word that has been seen to be a successor to its held word. It then repeats the process by finding a successor to that word in turn and carrying on iteratively until it thinks it’s said enough. It reaches that conclusion by stopping at a word that was prior to a punctuation mark in the training text. It then returns to input mode again to let you respond, and so on.

    It isn’t very realistic but I hereby challenge anyone to do better in 71 lines of code !! This is a great challenge for any budding Pythonists, and I just wish I could open the challenge to a wider audience than the small number of visitors I get to this blog. To code a bot that is always guaranteed to be grammatical must surely be closer to several hundred lines, I simplified hugely by just trying to think of the simplest rule to give the computer a mere stab at having something to say.

    Its responses are rather impressionistic to say the least ! Also you have to put what you say in single quotes.

    I used War and Peace for my “corpus” which took a couple of hours for the training run, use a shorter file if you are impatient…

    here is the trainer

    #lukebot-trainer.py
    import pickle
    b=open('war&peace.txt')
    text=[]
    for line in b:
        for word in line.split():
            text.append (word)
    b.close()
    textset=list(set(text))
    follow={}
    for l in range(len(textset)):
        working=[]
        check=textset[l]
        for w in range(len(text)-1):
            if check==text[w] and text[w][-1] not in '(),.?!':
                working.append(str(text[w+1]))
        follow[check]=working
    a=open('lexicon-luke','wb')
    pickle.dump(follow,a,2)
    a.close()
    

    Here is the bot:

    #lukebot.py
    import pickle,random
    a=open('lexicon-luke','rb')
    successorlist=pickle.load(a)
    a.close()
    def nextword(a):
        if a in successorlist:
            return random.choice(successorlist[a])
        else:
            return 'the'
    speech=''
    while speech!='quit':
        speech=raw_input('>')
        s=random.choice(speech.split())
        response=''
        while True:
            neword=nextword(s)
            response+=' '+neword
            s=neword
            if neword[-1] in ',?!.':
                break
        print response
    

    You tend to get an uncanny feeling when it says something that seems partially to make sense.

提交回复
热议问题