基于图灵机器人接口的简单NLP学习

来源:互联网 发布:水果竞猜php源码 编辑:程序博客网 时间:2024/05/22 12:33

说明

  • 图灵机器人提供在线接口,用户可自行注册学习,注册后官方提供想用的接口和连接方式,仅仅由于兴趣,做一个相当简单的聊天机器人,并开放核心源码,希望各位有闲情逸致的同胞可以继续丰富修改或扩展。
  • 本品仅供学习使用,代码多为开源库函数,各位同仁自行丰富。实现功能就是和简单的在线机器人交流。
  • 由于移动客户端以及在线网页上这种产品相当丰富完备,因此只针对windows用户实现桌面版本,也可作为新手的入手学习资料,代码未经修饰,显示效果单一,有兴趣和有时间的可以自行丰富。
  • 该机器人设计的内容有 聊天、笑话、故事、成语接龙、吉凶、新闻、星座、生活百科、图片(链接)、天气、菜谱、快递、数值计算、飞机票以及火车票查询(链接)、日期 等内容
  • 希望使用过这个程序的同胞可以反馈一下:你的问题是否得到满意的回答,如果没有,那么是什么问题难住这位在线机器人呢? 这将作为NLP知识库,对个性化的机器人提供NLP学习途径(哈哈。。。)
  • 本应用使用java开发,jdk1.7,64位环境,提供可执行jar包与可执行exe文件。
    点此下载
  • 此外提供一个IOS下的学习源码,类似微信风格

核心代码

    public class Ro_Online {    JFrame f=new JFrame("机器人-雨田");    JTextArea ta_chat=new JTextArea(20,40);    JTextArea ta_send=new JTextArea(5,34);      JButton send=new JButton("发送");    JLabel jl=new JLabel(" ");    JButton clear=new JButton("清空");    JPanel p=new JPanel();    JPanel p_bottom=new JPanel();    JPanel p_bottom1=new JPanel();    String input=null;    JLabel js=new JLabel();    JPanel jp=new JPanel();    TulingApiProcess robo=new TulingApiProcess();    String text=null;    PopupMenu pMeun=new PopupMenu();    MenuItem mItemCopy=new MenuItem("复制");    MenuItem mItemPaste=new MenuItem("粘贴");     //MenuItem mItemCut=new MenuItem("剪切");    MouseListener mouse=new MouseListener(){        @Override        public void mouseClicked(MouseEvent e) {            // TODO Auto-generated method stub            if(e.getButton()==MouseEvent.BUTTON3){                pMeun.show(p, e.getX(), e.getY());              }        }        @Override        public void mousePressed(MouseEvent e) {            // TODO Auto-generated method stub}        @Override        public void mouseReleased(MouseEvent e) {            // TODO Auto-generated method stub                  }        @Override        public void mouseEntered(MouseEvent e) {            // TODO Auto-generated method stub                  }        @Override        public void mouseExited(MouseEvent e) {            // TODO Auto-generated method stub                  }           };      public  void Init(){                JPanel p_chat=new JPanel();         ta_chat.setEditable(false);        ta_chat.setLineWrap(true);        ta_chat.setForeground(Color.BLUE);        //ta_chat.add(pMeun);        pMeun.add(mItemCopy);        mItemCopy.addActionListener(new ActionListener(){            @Override            public void actionPerformed(ActionEvent e) {                // TODO Auto-generated method stub                text=ta_chat.getSelectedText();                StringSelection select=new StringSelection(text);                Clipboard clip=Toolkit.getDefaultToolkit().getSystemClipboard();                clip.setContents(select, null);            }                   });        pMeun.add(mItemPaste);        ta_chat.addMouseListener(mouse);        p_chat.add(new JScrollPane(ta_chat));               p_bottom.setSize(5,42);        send.setSize(6, 10);        clear.setSize(6, 10);        p_bottom.setLayout(new FlowLayout());               p_bottom1.setLayout(new BorderLayout());        p_bottom1.add(send,BorderLayout.NORTH);        send.addActionListener(new ActionListener(){            public void actionPerformed(ActionEvent e){                input=ta_send.getText();                if(input.equals("")){                    ta_chat.append("!**为输入任何语句**!\n");                }else{                    ta_chat.append("你:\n    "+input+'\n');                    ta_chat.append("图灵机器人:\n");                    ta_chat.append(strTowrap(robo.getTulingResult(input)));                                 }                ta_send.setText("");            }        });        p_bottom1.add(jl,BorderLayout.CENTER);        p_bottom1.add(clear,BorderLayout.SOUTH);        clear.addActionListener(new ActionListener(){            public void actionPerformed(ActionEvent e){                ta_chat.setText("");            }        });        ta_send.setEditable(true);              ta_send.addKeyListener(new KeyAdapter(){//回车发送            @Override            public void keyPressed(KeyEvent e){//              ActionMap am=ta_send.getActionMap();//              am.getParent().remove();                if(e.getKeyCode()==KeyEvent.VK_ENTER){                    input=ta_send.getText();                    ta_send.setText("");                    ta_chat.append("你:\n    "+input+'\n');                    ta_chat.append("图灵机器人:\n");                    ta_chat.append(strTowrap(robo.getTulingResult(input)));                                 }            }        });             p_bottom.add(ta_send);        p_bottom.add(p_bottom1);            p.setLayout(new BorderLayout());        p.add(p_chat,BorderLayout.NORTH);        p.add(p_bottom,BorderLayout.CENTER);        p.add(pMeun);        p.addMouseListener(mouse);        try {           UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");        } catch (ClassNotFoundException e1) {            // TODO Auto-generated catch block            e1.printStackTrace();        } catch (InstantiationException e1) {            // TODO Auto-generated catch block            e1.printStackTrace();        } catch (IllegalAccessException e1) {            // TODO Auto-generated catch block            e1.printStackTrace();        } catch (UnsupportedLookAndFeelException e1) {            // TODO Auto-generated catch block            e1.printStackTrace();        }        //f.setBounds(0, 0, 400, 600);        jp.setLayout(new BorderLayout());        jp.add(p,BorderLayout.WEST);                                            JPanel pa=new JPanel(){            @Override            public void paintComponent(Graphics g) {                ImageIcon icon =                        new ImageIcon("robot.jpg");                // 重新绘制图片大小                //super.paint(g);                g.drawImage(icon.getImage(), 10, 20, 300,440,null);            }        };        jp.add(pa,BorderLayout.CENTER);        f.setSize(785,515);        f.setLocation(250, 75);        f.setResizable(false);        f.add(jp);        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            f.setVisible(true);    }       public static String strTowrap(String str){        String []s=str.split("<br>");        int n=s.length;        StringBuffer read=new StringBuffer();         for(int i=0;i<n;i++){            read.append("    "+s[i]+"\n");        }        return read.toString();    }    public static void main(String[]args){        new Ro_Online().Init();    }}
public class TulingApiProcess {    /**     * 调用图灵机器人api接口,获取智能回复内容,解析获取自己所需结果     * @param content     * @return     */    public String getTulingResult(String content){        /** 此处为图灵api接口,参数key需要自己去注册申请 */        String apiUrl = "http://www.tuling123.com/openapi/api?key=************&info=";//此处****为申请后获得的key        String param = "";        try {            param = apiUrl+URLEncoder.encode(content,"utf-8");        } catch (UnsupportedEncodingException e1) {            e1.printStackTrace();        } //将参数转为url编码        /** 发送httpget请求 */        HttpGet request = new HttpGet(param);        String result = "";        try {            HttpResponse response = HttpClients.createDefault().execute(request);            if(response.getStatusLine().getStatusCode()==200){          /** 返回码为200,表明成功返回(此外,常见的失败返回码:404未找到;502网关错误;503服务不可用;504网关超时)*/                result = EntityUtils.toString(response.getEntity());            }        } catch (ClientProtocolException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        }        /** 请求失败处理 */        if(null==result){            return "对不起,你说的话真是太高深了   !>_<!  ";        }        try {            JSONObject json = new JSONObject(result);            //参考图灵机器人api文档            if(100000==json.getInt("code")){//文本类                result = json.getString("text");            }            if(200000==json.getInt("code")){//链接类                result = json.getString("url");            }        } catch (JSONException e) {            e.printStackTrace();        }        return result;    }}
0 0