C#面向對象Chatbot智能版

C#面向對象Chatbot智能版c#

你們好,我是一個C#的初學者,老師平時叫咱們寫C#控制檯程序,我總結了一些所學的知識,寫了一個升級版的聊天機器人,經過文件操着,機器人具備智能查找,學習功能。和你們分享一下,但願能獲得高手指點進步。函數

一、Project:chatbot 二、功能:聊天、報時間 三、預置聊天學習,智能學習,作數學題 五、關鍵技術:讀取文件,寫入文件 六、打印聊天內容學習

2、要求測試

一、成員分工:主界面、預約義庫、計算器 二、技術核心內容:文件流、write,read,array; 三、優化過程優化

<!-- lang: c# -->

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

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; //定義機器人名字spa

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("*  一、select chat bot press \"A\" or \"B\"   *");
        Console.WriteLine("*  二、chat bot include weather、date、time   *");
        Console.WriteLine("*  三、Exit input \"exit\" or \"!e\"          *");
        Console.WriteLine("*  四、Calculator function, enter a formula   *");
        Console.WriteLine("*  五、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)*/)    //一、核心關鍵捕獲,智能匹配//
            {
                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(); //調用回答方法
    }

}

}指針

相關文章
相關標籤/搜索