Skip to content

Python聊天机器人1


作者: GMCY
分类: CSDN
创建时间: 2020年04月26日
更新时间: 2020年04月26日

分享一个自己用Python写的聊天机器人 可以的话 望各位不要嫌弃

运行效果

python
==============================程序开始==============================
小艾: 主人是否要加载学习模块
主人(y/n):y
小艾: 主人请吩咐
主人: 你是谁哎呀?
小艾: 你不就是最最喜欢我的人吗?
主人: 真的吗?我太高兴了
小艾: 高兴时不需要理由的,我也找点乐子去!
主人: 聊天机器人
小艾: 不可泄露
主人: 吃了你
小艾: 我不用吃东西,也会有无穷的力量。
主人: 北京是哪里
小艾: 北京是中华人民共和国的首都,中国中央四个直辖市之一
主人: 自行车v把你们那边v出现在
小艾: 你们、他们、我们
主人: sasfdgfngertfgh
小艾: 请主人输入要学习语句(n退出学习)
主人: 佛了你
小艾: 请主人输入回答语句(n退出学习)
主人: 别呀,主人
小艾: 加载中…
小艾: 加载完成
主人: 佛了你
小艾: 别呀主人
主人: 真是我佛了你了
小艾: 别呀主人
主人: exit
==============================程序结束==============================

完整代码

python
# _*_ codding:utf-8 _*_
# Created by GMCY
# https://blog.csdn.net/weixin_46554689
# 2020/4/26

import jieba

def ai_StrSplit(String):
    """
    Decompose the string into a list           # 将字符串分解为一个列表
    :param String: The string to be decomposed # 要分解的字符串
    :return: String_lt                         # 分解后的字符串列表
    """
    String_lt = jieba.lcut(String, cut_all=True)    # 要引入jieba库
    String1 = jieba.lcut(String, cut_all=True)
    String2 = jieba.lcut(String, cut_all=True)
    String3 = jieba.lcut(String, cut_all=True)
    String3.append('')
    for Str1 in String1:
        String2.remove(Str1)
        for Str2 in String2:
            try:
                String3.remove(Str1)
            except:
                pass
            try:
                String3.remove(Str2)
            except:
                pass
            for Str3 in String3:
                String_lt.append(Str1 + Str2 + Str3)
    return String_lt

def ai_MatchSiple(path, String):
    """
    Matches the dictionary to a single string  # 将字典匹配到单个字符串
    :param path: The dictionary to match       # 匹配的字典
    :param String: The string to match         # 要匹配的字符串
    :return: lt_ms                             # 匹配结果与判断(1有/0无)的列表
    """
    errow_matchsplit = 0
    back = None
    with open(path, 'r', encoding='utf-8') as f:     # 注意编码
        while errow_matchsplit == 0:
            f1 = f.readline().split('\n')[0]
            f2 = f.readline().split('\n')[0]
            f3 = f.readline()
            if String == f1:
                back = f2
                errow_matchsplit = 1
                break
            if f1 == '' or f2 == '':
                break
    lt_ms = [back, errow_matchsplit]
    return lt_ms

def ai_MatchHeight(path, String_lt):
    """
    Matches the dictionary with a list of strings # 用字符串列表匹配字典
    :param path: The dictionary to match          # 匹配的字典
    :param String_lt: List of strings to match    # 要匹配的字符串列表
    :return: lt_mh                                # 匹配结果与判断(1有/0无)的列表
    """
    errow_matchheight = 0
    back = None
    with open(path, 'r', encoding='utf-8') as f:     # 注意编码
        while errow_matchheight == 0:
            f1 = f.readline().split('\n')[0]
            f2 = f.readline().split('\n')[0]
            f3 = f.readline()
            for String in String_lt:
                if String == f1:
                    back = f2
                    errow_matchheight = 1
                    break
            if f1 == '' or f2 == '':
                break
    lt_mh = [back, errow_matchheight]
    return lt_mh

def ai_study(path, study_start, study_end):
    """
    Open the dictionary and write the match statement and the match result # 打开字典并编写匹配语句和匹配结果
    :param path: The dictionary to open                                    # 要查的字典
    :param study_start: Dictionary matching statements                     # 词典匹配语句
    :param study_end: The dictionary returns the result                    # 字典返回结果
    :return: None                                                          # 无返回
    """
    with open(path, 'a', encoding='utf-8') as f:     # 注意编码
        f.write(study_start+'\n')
        f.write(study_end+'\n')
        f.write('\n')


if __name__ == '__main__':
    path = r'ai词库.txt'                       # 要匹配的词典
    print('='*20 + '程序开始' + '='*20)
    print('小艾: 主人是否要加载学习模块')
    errow_study = input('主人(y/n):')
    print('小艾: 主人请吩咐')
    String = input('主人: ')
    while String != 'exit':
        a1 = ai_MatchSiple(path=path, String=String)
        show = a1[0]
        errow_matchsimple = a1[1]
        if errow_matchsimple == 0:
            String_lt = ai_StrSplit(String=String)
            a2 = ai_MatchHeight(path=path, String_lt=String_lt)
            show = a2[0]
            errow_matchhight = a2[1]
            if errow_matchhight == 0 and (errow_study == 'y' or errow_study == 'yes'):
                print('小艾: 请主人输入要学习语句(n退出学习)')
                study_start = input('主人: ')
                if study_start != 'n' and study_start != 'no':
                    print('小艾: 请主人输入回答语句(n退出学习)')
                    study_end = input('主人: ')
                    if study_end != 'n' and study_end != 'no':
                        print('小艾: 加载中…')
                        ai_study(path=path, study_start=study_start, study_end=study_end)
                        print('小艾: 加载完成')
            else:
                print('小艾:', show)
        else:
            print('小艾:', show)
        String = input('主人: ')
    print('='*20 + '程序结束' + '='*20)

1,ai_StrSplit() 的使用方法

python
String = "聊天机器人之字符串分解"
show = ai_StrSplit(String)
#show = ai_StrSplit(String=String)
print(show)

ai_StrSplit() 分解后的列表

python
['聊天机器人字符串', '聊天天机机器人', '聊天天机字符串', '聊天机器机器人', '聊天机器字符串', '聊天机器人字符', '聊天机器人分解', '聊天字符字符串', '聊天字符串分解', '聊天天机机器', '聊天天机字符', '聊天天机分解', '聊天机器字符', '聊天机器分解', '聊天机器人之', '聊天之字符串', '聊天字符分解', '机器人字符串', '聊天天机之', '聊天机器之', '聊天机器人', '聊天之字符', '聊天之分解', '聊天字符串', '天机机器人', '天机字符串', '机器机器人', '机器字符串', '机器人字符', '机器人分解', '字符字符串', '字符串分解', '聊天天机', '聊天机器', '聊天字符', '聊天分解', '天机机器', '天机字符', '天机分解', '机器字符', '机器分解', '机器人之', '之字符串', '字符分解', '机器人', '字符串', '聊天之', '天机之', '机器之', '之字符', '之分解', '聊天', '天机', '机器', '字符', '分解', '之']

2,ai_MatchSimple() 的使用方法

python
path = r'ai词库.txt'
String = '你是谁'
show = ai_MatchSiple(path, String)
#show = ai_MatchSiple(path=path, String=String)
print(show)     # 匹配后果与判断(1有/0无)的列表
print(show[0])  # 匹配的结果(有: 结果/无: None)
print(show[1])  # 匹配结果的是否(1是/0否)

ai_MatchSimple() 简单的匹配后的结果

python
['我是我', 1]
我是我
1

3,ai_MatchHeight() 的使用方法

python
path = r'ai词库.txt'
String_lt = ['谁是你', '你是谁']
show = ai_MatchHeight(path, String_lt)
#show = ai_MatchHeight(path=path, String_lt=String_lt)
print(show)     # 匹配后果与判断(1有/0无)的列表
print(show[0])  # 匹配的结果(有: 结果/无: None)
print(show[1])  # 匹配结果的是否(1是/0否)

ai_MatchHeight() 简单的匹配后的结果

python
['我是我', 1]
我是我
1

4, ai_study()的使用方法

python
path = r'ai词库.txt'
study_start = '你会什么'
study_end = '我吃东西厉害(。・∀・)ノ'
ai_study(path, study_start, study_end)
#ai_study(path=path, study_start=study_start, study_end=study_end)

运行前ai词库.txt的一部分

python
在?



你才吹

运行后ai词库.txt的一部分

python
在?



你才吹

你会什么
我吃东西厉害(。・∀・)ノ
python
词库的规律:
第3n-2行: 匹配的关键词和语句
第3n-1行: 匹配的结果
第3n行:   空一行分界
末尾行:   空一行用与写入