关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

C#面向对象Chatbot智能版代码是什么

发布时间:2020-02-04 17:45:00

C#面向对象Chatbot智能版


大家好,我是一个C#的初学者,老师平时叫我们写C#控制台程序,我总结了一些所学的知识,写了一个升级版的聊天机器人,通过文件操着,机器人具有智能查找,学习功能。和大家分享一下,希望能得到高手指点进步。


1、Project:chatbot 2、功能:聊天、报时间 3、预置聊天学习,智能学习,做数学题 5、关键技术:读取文件,写入文件 6、打印聊天内容


二、要求


1、成员分工:主界面、预定义库、计算器 2、技术核心内容:文件流、write,read,array; 3、优化过程


<!-- lang: c# -->

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO;


namespace ProjectC_sharp { class chatbot_61 { public static void Main(string[] args) { methot met = new methot(); //实例化方法过程 met.showUI(); //UI string chat; bool flag = false; //判断 string user; //定义用户名 string Robot; //定义机器人名字


    start:

        {

            Console.WriteLine("**********************************************************");

            Console.WriteLine("请选择机器人>>>>>>>[A :\"小屌丝\"]\t[B:\"小橘子\"]<<<<<<< ");  //start set chat bot

            Console.WriteLine("*        help>>>help                                                *");

            Console.WriteLine("**********************************************************");

        }

        Console.WriteLine("请输入您的姓名:");

        user = Console.ReadLine();

        Console.WriteLine("请选择机器人:");

        string set = Console.ReadLine();  //选择机器人

        if (set == "A" || set == "小屌丝" || set == "a")

        {

            met.ASayhello(user);

            Robot = "小屌丝";

        }

        else if (set == "B" || set == "小橘子" || set == "b")

        {

            met.BSayhello(user);

            Robot = "小橘子";

        }

        else

        {

            Console.Clear();

            Console.ForegroundColor = ConsoleColor.Red;

            Console.WriteLine("--------!waring:你的输入不正确,请重新输入----------\a\a\a\n");

            met.help(); //调出帮助菜单


            Console.WriteLine();

            Console.ForegroundColor = ConsoleColor.White;  //白色

            goto start;  //转到开始部分


        }

        methot.mcname = Robot;  //静态传值机器人名字

        methot.user = user; //静态传用户姓名


        do //机器人循环说话Main

        {

            Console.Write(user+">>说:");

            chat = Console.ReadLine();

            Console.WriteLine();

            met.Speak(chat,flag);

            if (chat == "exit" || chat == "EXIT")

                break;

        } while (true); //结束程序

        Console.Clear();

        Console.WriteLine();

        Console.WriteLine();

        Console.WriteLine();

        Console.WriteLine("\t\t>>>>系统已成功退出,按任意键结束程序!<<<<");

        Console.ReadKey();



    }

}


class propert

{

    //机器人属性: 年龄、性别、姓名

    private string name;

    private int age;

    private string sex;


    public string Name

    {

        set { this.name = value; }

        get { return name; }

    }


    public int Age

    {

        set { this.age = value; }

        get { return age; }

    }


    public string Sex

    {

        set { this.sex = value; }

        get { return sex; }


    }


    public propert(string N, int A, string S)

    {

        name = N;

        age = A;

        sex = S;


    }


}


class methot

{

    //机器人的名字

    public static string mcname;

    //用户的名字

    public static string user;


   /*

    以下函数是机器人的方法

    

    */


    //小屌丝Sayhello

    public string ASayhello(string user)

    {

        propert pr = new propert("小屌丝", 18, "男");

        Console.WriteLine("{0}:你好,我叫<{1}>,我{2}岁了,我是{3}生\a", pr.Name = "小屌丝", pr.Name = "小屌丝", pr.Age, pr.Sex);

        //Console.WriteLine("请问你叫什么名字呀?\a");

        //string user = Console.ReadLine();

        Console.WriteLine("{0}:{1}很高兴和你聊天!\a", pr.Name, user);

        return user;

    }


    //小橘子Sayhello

    public void BSayhello(string user)

    {

        propert pg = new propert("小橘子", 16, "女");

        Console.WriteLine("{0}:你好我叫<{1}>,我{2}岁了,我是{3}生\a", pg.Name = "小橘子", pg.Name = "小橘子", pg.Age, pg.Sex);

        Console.WriteLine("{0}:{1}很高兴和你聊天!\a", pg.Name, user);


    }


    //UI

    public void showUI()

    {

        Console.ForegroundColor = ConsoleColor.Green;

        Console.WriteLine("\t\t*****************************************");

        Console.WriteLine("\t\t*                                       *");

        Console.WriteLine("\t\t--------------wecomel chat bot---------- ");

        Console.WriteLine("\t\t*              聊天机器人               *");

        Console.WriteLine("\t\t*                                       *");

        Console.WriteLine("\t\t*                 >> 项目五组:农夫三拳  *");

        Console.WriteLine("\t\t*****************************************");

        Console.ReadKey();

        Console.ForegroundColor = ConsoleColor.White;

        Console.Clear();


    }


    /*help帮助中心*/


    public void help()

    {

        Console.WriteLine("**********************************************");

        Console.WriteLine("*                                            *");

        Console.WriteLine("*            CHAT BOT HELP CENTER            *");

        Console.WriteLine("*  1、select chat bot press \"A\" or \"B\"   *");

        Console.WriteLine("*  2、chat bot include weather、date、time   *");

        Console.WriteLine("*  3、Exit input \"exit\" or \"!e\"          *");

        Console.WriteLine("*  4、Calculator function, enter a formula   *");

        Console.WriteLine("*  5、the first number second number         *");

        Console.WriteLine("**********************************************");

        Console.ReadKey();

        Console.Clear();

    }


    /*查询时间*/

    public void datetime()

    {

        DateTime current = DateTime.Now;

        int year = current.Year;  //获取年

        int month = current.Month;  //获取月

        int day = current.Day;//获取日

        int hours = current.Hour;//获取小时

        int minute = current.Minute;// 获取分钟

        int second = current.Second;//获取秒

        if (hours <=6)

        {

            Console.WriteLine("现在是凌晨。\a");

        }

        else if (hours <= 9)

        {

            Console.WriteLine("早上好!\a");

        }

        else if (hours <=18)

        {

            Console.WriteLine("下午好!\a");

        }

        else if(hours<=24)

        {

          Console.WriteLine("晚上好!");

        }

        else

        {

            Console.WriteLine("__获得时间出错,请调试!");

        }


        Console.WriteLine("现在是{0}年{1}月{2}日{3}时{4}分{5}秒\a", year, month, day, hours, minute, second);


    }


    /*计算器模块*/

    public void Calculator()

    {

        double Number1, Number2;

        char option;

        double Result;

        bool flag = true;

        while(flag)

        {

            try

            {

                Console.WriteLine("Enter the Fist Number");

                Number1 = double.Parse(Console.ReadLine());

                Console.WriteLine("Enter the Second Number");

                Number2 = double.Parse(Console.ReadLine());

                Console.WriteLine("Mian Menum");

                Console.WriteLine("1.Additon");

                Console.WriteLine("2.Subtraction");

                Console.WriteLine("3.Multiplication");

                Console.WriteLine("4.Division");

                Console.WriteLine("Enter the Operation you want to perform");

                option = char.Parse(Console.ReadLine());

                switch (option)

                {

                    case '1':

                        Result = Number1 + Number2;

                        Console.WriteLine("The result of addition is :{0}", Result); break;

                    case '2':

                        Result = Number1 - Number2;

                        Console.WriteLine("The result of subtraction is :{0}", Result); break;

                    case '3':

                        Result = Number1 * Number2;

                        Console.WriteLine("The result of Multiplication if :{0}", Result); break;

                    case '4':

                        if (Number2 == 0)

                        {

                            Console.WriteLine("Divisor canot be zero");

                        }

                        else

                        {

                            Result = Number1 / Number2;

                            Console.WriteLine("The result of divison is :{0}", Result);

                        }

                        break;

                    default: Console.WriteLine("Invalid Option"); break;

                }

                flag = false;

            }

            catch

            {

                flag = true;

                Console.WriteLine("你的输入正确,请重新输入!\a\a\a");

            }

        }


    }


    /*test temp*/

    public void FileRead()

    {

        string FILENAME = "J:\\C_sharp_Code\\Project\\Answer.txt";

        FileStream fs = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);

        StreamReader sr = new StreamReader(fs, Encoding.Default);

        string reder = sr.ReadLine();

        while (reder != null)

        {

            Console.WriteLine(reder);

            reder = sr.ReadLine();

        }

        sr.Close();

        fs.Close();


    }



    //机器人预定义内置库回复

    public void Speak(string chat,bool flag)

    {


        //string weather="天气";

        //string time="时间";

        //string Calculate = "计算";

        //string[] str = { "天气","长沙","今天" };

        bool b;

       

        int count = 0;

        string FILENAME1 = "J:\\C_sharp_Code\\Project\\Question.txt";

        

        FileStream fs1 = new FileStream(FILENAME1, FileMode.Open, FileAccess.Read);

       

        StreamReader sr1 = new StreamReader(fs1, Encoding.Default);

        

        string reader1;

        reader1 = sr1.ReadLine();

        while (reader1 != null)

        {

            count++;

            if (b = reader1.Contains(chat) /*|| chat.Contains(reader1)*/)//reader1.Contains(chat)

            {

               // chat = reader1;  //reder

                flag = true;

                break;

            }

            reader1 = sr1.ReadLine();

            

        }

       // Console.WriteLine("判断:{0}", flag); Test 判断是否为真

        fs1.Close();

        sr1.Close();


        /*小调试*/

      //  Console.WriteLine("count1={0}",count);  //测试count1

       // Console.WriteLine("chat={0}",chat);  //测试chat

      //  Console.WriteLine(flag);               //测试真假


        /*预定义内置库 weather 、计算器、简单回复*/


        if (chat.Contains("weather") || chat.Contains("天气") || chat.Contains("长沙"))             //关键字提取  天气

        {

            Console.WriteLine("{0}说>>:长沙的天气多云转晴\a",mcname);

        }

        //b = chat.Contains(Calculate)

        else if (chat.Contains("时间") || chat.Contains("几点") || chat.Contains("钟")||chat.Contains("time"))             //关键字提取   时间

        {

            // Console.WriteLine("现在的时间我还真不知道!");

            Console.Write("{0}说>>:",mcname);

            datetime();                                       //调用时间函数

        }

        else if (chat.Contains("计算") || chat.Contains("数学")||chat.Contains("做题"))

        {

            Console.ForegroundColor = ConsoleColor.Yellow; //黄色

            Console.WriteLine("{0}说>>:好的,正在为你启动计算器",mcname);

            Calculator();

            Console.WriteLine();

            Console.WriteLine();

            Console.ForegroundColor = ConsoleColor.White;  //白色

        }


      

        else if (chat.Contains("....") || chat.Contains("...") || chat.Contains("..") || chat.Contains("."))

        {

            Console.WriteLine("{0}说>>:这斑斑点点,不能彰显你的沉默,只会昭示你左右手的寂寞~",mcname);

        }

       

        else if(chat.Trim().Equals(string.Empty))  //判断用户输入的是否空格

        {

            Console.WriteLine("{0}说>>:您什么也没有输入\a",mcname);

        }

        else if (chat=="")

        {

            Console.WriteLine("{0}说>>:你一句话也没有说啊,你在吐口水吗?\a",mcname);

        }

        else if (flag)

        {

            ReaderQuestion(chat,mcname); //question

        }


        else

        {

            //

            bool yn = true;

            Console.WriteLine("{0}说>>:~噢我没有听懂,你教我好吗?",mcname);


            while (yn)

            {

                Console.ForegroundColor = ConsoleColor.DarkCyan;

                Console.WriteLine("{0}说>>:教我学习吧(Y\\N)?\a",mcname);

                Console.Write("{0}>>说:",user);

                string repor = Console.ReadLine();

                if (repor == "y" || repor == "Y")

                {

                    Console.ForegroundColor = ConsoleColor.Red;

                    Console.WriteLine();

                    Console.WriteLine();

                    Console.WriteLine();

                    Console.WriteLine("\t\t>>>>>>>>>机器人已进入学习模式<<<<<<<<<<<<");

                    Console.WriteLine();

                    Console.ForegroundColor = ConsoleColor.DarkCyan;

                    WriteQuestion();  //调用学习方法

                    yn = false;


                }

                else if (repor == "n" || repor == "N")

                {

                    Console.WriteLine("{0}说>>:您取消了学习,哼~居然不教我。\a",mcname);

                    yn = false;


                }

                else

                {

                    Console.WriteLine("{0}说>>:您的输入不正确\a",mcname);

                    yn = true;

                }


                Console.WriteLine();

                Console.ForegroundColor = ConsoleColor.White;  //白色


            }


        }



    }



    /*机器人学习*/


    /*test Reader*/

    public void ReadAnser() //读取Answer—A文件

    {

        string FILENAME = "J:\\C_sharp_Code\\Project\\Answer.txt";

        FileStream fs = new FileStream(FILENAME, FileMode.Open, FileAccess.Read);

        StreamReader sr = new StreamReader(fs, Encoding.Default);

        string reder = sr.ReadLine();

        while (reder != null)

        {

            Console.WriteLine(reder);

            reder = sr.ReadLine();

        }

        sr.Close();

        fs.Close();




    }


    /*机器人智能匹配模块*/


    public void ReaderQuestion(string chat, string name ) //读取Questioin第二文件B

    {

        bool b;  //flag

        int count = 0;

        string FILENAME1 = "J:\\C_sharp_Code\\Project\\Question.txt";

        string FILENAME2 = "J:\\C_sharp_Code\\Project\\Answer.txt";

        FileStream fs1 = new FileStream(FILENAME1, FileMode.Open, FileAccess.Read);

        FileStream fs2 = new FileStream(FILENAME2, FileMode.Open, FileAccess.Read);

        StreamReader sr1 = new StreamReader(fs1, Encoding.Default);

        StreamReader sr2 = new StreamReader(fs2, Encoding.Default);

        string reader1;

        reader1 = sr1.ReadLine();

        while (reader1 != null)

        {

            count++;

            if (b = reader1.Contains(chat)/*||chat.Contains(reader1)*/)    //1、核心关键捕获,智能匹配//

            {

                chat = reader1;  //reder

                //Console.WriteLine(chat);

                break;         //找到坐标位置跳出去

            }

            reader1 = sr1.ReadLine();

            // Console.WriteLine(chat);

        }


        //指针指向Anser

        //Console.WriteLine("count={0}",count); //坐标位置测试

        string reder2 = "null没有读到";

        for (int i = 1; i <= count; i++)

        {

            reder2 = sr2.ReadLine();

            chat = reder2;

        }

       

            Console.ForegroundColor = ConsoleColor.Green;

            Console.WriteLine("{0}说>>{1}\a", name, chat);  //机器人的回答

            Console.WriteLine();



        sr1.Close();

        fs1.Close();

        sr2.Close();

        fs2.Close();

    }



    /*Write机器人学习过程*/



    public void WriteAnwser()  //WriterAnswer_  B文件

    {

        string FILENAME = @"J:\C_sharp_Code\Project\Answer.txt";

        FileStream feel = new FileStream(FILENAME, FileMode.Append, FileAccess.Write);

        StreamWriter sw = new StreamWriter(feel, Encoding.Default);

        Console.WriteLine("请输入答案:");

        //写入文件

        string str = Console.ReadLine();

        sw.WriteLine(str + "\n");

        sw.Flush();

        sw.Close();

        feel.Close();

        Console.WriteLine();

        Console.ForegroundColor = ConsoleColor.Blue;

        Console.WriteLine("{0}说>>:OK,我学会了!",mcname);

        Console.WriteLine("~亲咱们继续聊!");

        Console.WriteLine();

        Console.WriteLine();

        Console.ForegroundColor = ConsoleColor.Red;

        Console.WriteLine("\t\t>>>>>>>>>机器人学习已成功<<<<<<<<<<<<");

        Console.WriteLine();

        Console.ForegroundColor = ConsoleColor.White;  //白色


    }


    public void WriteQuestion()  //Write Question  A文件

    {

        string FILENAME = @"J:\C_sharp_Code\Project\Question.txt";

        FileStream feel = new FileStream(FILENAME, FileMode.Append, FileAccess.Write);

        StreamWriter sw = new StreamWriter(feel, Encoding.Default);


        //写入文件

       

        Console.ForegroundColor = ConsoleColor.Green;  //绿色

         Console.WriteLine("请输入问题:");

         string str = Console.ReadLine();

        sw.WriteLine(str + "\n");

        sw.Flush();

        sw.Close();

        feel.Close();

        WriteAnwser(); //调用回答方法

    }


}



/template/Home/Zkeys/PC/Static