rule-base机器人1

1、最基础的fi—else问答
import random
# 打招呼
greetings = ['hola', 'hello', 'hi', 'Hi', 'hey!','hey']
# 回复打招呼,random.choice意思是随机选取内容
random_greeting = random.choice(greetings)

# 对于“你怎么样?”这个问题的回复
question = ['How are you?','How are you doing?']
# “我很好”
responses = ['Okay',"I'm fine"]
# 随机选一个回
random_response = random.choice(responses)

while True:
    # 输入用>>> 表示
    userInput = input(">>> ")
    if userInput in greetings:
        print(random_greeting)
    elif userInput in question:
        print(random_response)
    # 除非你说“拜拜”
    elif userInput == 'bye':
        break
    else:
        print("I did not understand what you said")

2、改进

from nltk import word_tokenize

import random

# 打招呼

greetings = ['hola', 'hello', 'hi', 'Hi', 'hey!','hey']

# 回复打招呼

random_greeting = random.choice(greetings)

# 对于“假期”的话题关键词

question = ['break','holiday','vacation','weekend']

# 回复假期话题

responses = ['It was nice! I went to Paris',"Sadly, I just stayed at home"]

# 随机选一个回

random_response = random.choice(responses)

# 机器人跑起来

while True:

userInput = input(">>> ")

# 清理一下输入,看看都有哪些词

#nltk.sent_tokenize(text) #按句子分割

#nltk.word_tokenize(sentence) 把输入分词

cleaned_input = word_tokenize(userInput)

# set(A).isdisjoint(B)是意思看是否A和B有交集,返回true

if not set(cleaned_input).isdisjoint(greetings):

print(random_greeting)

elif not set(cleaned_input).isdisjoint(question):

print(random_response)

# 除非你说“拜拜”

elif userInput == 'bye':

break

else:

print("I did not understand what you said")

3、改进

我们可以用各种数据库,建立起一套体系,然后通过搜索的方式,来查找答案。

比如,最简单的就是Python自己的graph数据结构来搭建一个“地图”。

依据这个地图,我们可以清楚的找寻从一个地方到另一个地方的路径,

然后作为回答,反馈给用户。

#
# 建立一个基于目标行业的database
# 比如 这里我们用python自带的graph
graph = {'上海': ['苏州', '常州'],
         '苏州': ['常州', '镇江'],
         '常州': ['镇江'],
         '镇江': ['常州'],
         '盐城': ['南通'],
         '南通': ['常州']}


# 明确如何找到从A到B的路径
def find_path(start, end, path=[]):
    path = path + [start]
    if start == end:
        return path
    if start not in graph:
        return None
    for node in graph:
        if node not in path:
            newpath = find_path(node, end, path)
    return newpath
    print(find_path('上海', "镇江"))
    ['上海', '南通', '盐城', '镇江']

上面是通过输入的上海找到和镇江之间的关系的路径。


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值