⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 templatelanguagegenerator.java

📁 一个关于CHATBOT的程序(人式智能方面)
💻 JAVA
字号:
package ijp.assignment1.langen;
import java.util.Random;
import ijp.assignment1.utils.WordNetWrapper;
import java.util.ArrayList;
import java.util.List;
import java.util.HashMap;
import java.lang.String;
import java.util.HashSet;
import java.util.Iterator;
import net.didion.jwnl.data.POS;


/**
 * A simple template driven language generator. Used in IJP assignment 
 * 1 to generate language for the ChatBots 
 * 
 * @author Judy Robertson, Nigel Goddard
 */
public class TemplateLanguageGenerator implements LanguageGenerator {
    
	
	/**
	 * A collection of sentence templates which this language generator can use
	 */
	private ArrayList <SentenceTemplate> sentenceList  = new ArrayList <SentenceTemplate> ();
	
	/**
	 * A collection of canned text which can be seached to reply to the question
	 */
    private HashMap<String, String> replyMap;

	/**
	 * A random number which can be used to generate random sentence
	 */
	private Random randomGenerator;
	
	/**
	 * Creates 5 senence templates which will be used in starting a conversation 
	 */
    private SentenceTemplate template1;
    private SentenceTemplate template2;
    private SentenceTemplate template3;
    private SentenceTemplate template4;
    private SentenceTemplate template5;
    
   /**
    * A collection of returning synonyms
    */
   private ArrayList <String> synonymList=new ArrayList<String>();
   
    /**
	 * Creates a TemplateLanguageGenerator, sets up the sentence templates,
	 */		
	public TemplateLanguageGenerator() {
	    
		populateSentences();
		
		// Creates a random object which will be used in generating random sentence
		randomGenerator= new Random();
		
		//Fills all the templates into the sentenceList
		fillSentenceTemplates();
		
		
	}

	/**
	 * Sets up the sentence templates which can be used by the language generator
	 */	
	private void populateSentences() {
	    
	    //Sets up five templates which can be used by the language genarator
	    template1=new SentenceTemplate(SentenceTemplate.QUESTION,"What is your opinion on ||NOUN");
	    template2=new SentenceTemplate(SentenceTemplate.QUESTION,"How can I || VERB || with ||NOUN");
	    template3=new SentenceTemplate(SentenceTemplate.QUESTION,"Do you think that ||NOUN|| is ||Adjective");
	    template4=new SentenceTemplate(SentenceTemplate.REPLY,"I am very interested in ||NOUN||. can you tell me more in detail.");
        template5=new SentenceTemplate(SentenceTemplate.REPLY,"It may be caused by|| NOUN.You should check it again.");
        
    }

	/**
	 * Fills the five templates into the sentenceList
	 */	
    private void fillSentenceTemplates()
    {
        sentenceList.add(template1);
        sentenceList.add(template2);
        sentenceList.add(template3);
        sentenceList.add(template4);
        sentenceList.add(template5);
    }
  
	/**
	 * Generates a sentence using a randomly chosen template
	 *
     * @return A string containing the sentence
	 */
	public String generateSentence() {
	    //Generates a index which is a initial index being used in the following while loop
	    int index=randomGenerator.nextInt(sentenceList.size());
	    
	    /*Make sure that the start sentence is a question, otherwise, it will generate again*/
	    while(sentenceList.get(index).getSentenceType()!="question"){
	       index=randomGenerator.nextInt(sentenceList.size());
	   }
	   
	    //Calls the expandTemplate method to expand the template into a full sentence
	    String fullSentence=expandTemplate(sentenceList.get(index).getTemplate());
	    
	    return fullSentence;
		
	}
	
	/**
	 * Expands the template into a full sentence. The templates are strings
	 * consisting of canned text and instructions to generate more text. Canned
	 * segments and instructions are delimited by "||".
	 *
     * @param sentenceTemplate The template which will be expanded
	 * 
     * @return A string containing the sentence expanded out of the template
	 */  
	private String expandTemplate(String sentenceTemplate) {
	    
	    //Creates a WordNetWraaper object so that we can use the methods in it to
	    //generate random noun, verb and adjective.
	    WordNetWrapper wordNetW1=new WordNetWrapper();
	    
	    //Use replace method to replace the NOUN,VERB and Adjective with the random one
	    sentenceTemplate=sentenceTemplate.replace("NOUN",wordNetW1.getNounAtRandom());
	    sentenceTemplate=sentenceTemplate.replace("VERB",wordNetW1.getVerbAtRandom());
	    sentenceTemplate=sentenceTemplate.replace("Adjective",wordNetW1.getAdjectiveAtRandom());
	    sentenceTemplate=sentenceTemplate.replace("||"," ");
	    return sentenceTemplate;
	}

	
    
    /**
     * Use key word matching to generate a canned response to the specified
     * comment.
     * 
     * @param remark The input which we must respond to
     * 
     * @return A string containing a reply to the specified remark
     */
    private String keyWordMatch(String remark){
        //Initializes the HashMap object replyMap and fill all the known keywords
        //and related responses into the object.
        replyMap =new HashMap<String, String>();
        fillReplyMap();
        
        //Gets rid of the blank space in the begining of remark and converts all its
        //word to lower case.
        String inputLine=remark.trim().toLowerCase();
        
        //Divides the remark into a set of words and put them into an array, then
        //adds the elements of the array into the hashset
        String[ ] wordArray=inputLine.split(" ");
        HashSet<String> words=new HashSet<String>();
        for(String word:wordArray){
            words.add(word);
        }
        
        //Iterates over the words and check each of them with our known keywords in 
        //our map.
        Iterator<String> it=words.iterator();
        while(it.hasNext()){
            String word=it.next();
            String reply=replyMap.get(word);
            if(reply!=null){
                return reply;
            }
        }
            
            //if we get here,the word was not recognized.In this situation,we pick one 
            //of our default reply.
            return pickDeFaultReply();
        
    }
       
    
      
    /**
     * Enter all the known key words and their associated reponses into our reply map.
     */
    private void fillReplyMap()
    {
        replyMap.put("beatuiful","well,you know I havn't seen yet.\n"+"So can you describe more?\n");
        replyMap.put("war","It is really a bad thing\n");
        replyMap.put("finish","I don't know, may be a week or longer.");
    }
    
    /**
     * The following is our default reply.
     * 
     * @return A default reply which is set by the programmer at the beginning
     */
    public String pickDeFaultReply(){
        return "It sounds interesting, can you tell me more...";
    }

	/**
	 * Parse the input remark, and find a key word which we can respond to
     * 
	 * @param remark The input to be parsed
     * 
	 * @return A keyword from the input which will be used in the reply
	 */ 
	private String findKeyWord(String remark) {
	    
	    //Creates a WordNetWraaper object so that we can use its judgement method of noun
	    WordNetWrapper getWord=new WordNetWrapper();
	    String inputLine=remark.trim().toLowerCase();
        String[ ] wordArray=inputLine.split(" ");
        HashSet<String> words=new HashSet<String>();
        String keyWord=null;
        for(String word:wordArray)
        {
            words.add(word);
        }
        Iterator<String> it=words.iterator();
        while(it.hasNext()){
            keyWord=it.next();
            
            //To judge whether the keyword is a NOUN, if yes, return
            //the keyword, otherwise, loop again until there are no
            //word in the iterator.
            if(getWord.isNoun(keyWord)){
                return(keyWord);
            }
            else 
            continue;       
        }
        
        //To get here which means that there are no keyword in the remark,
        //we will return an information to system
        return("The system cannot find a keyword");
	}
	
	/**
	 * Generate a word list which is synonyms to the keyWord and expand the templates which 
	 * are specified in sentencePopulate.
	 * 
	 * @param keyWord The input that should be generated a synonym
	 * @return A string that contain the whole reply
	 */
	private String expandTemplateTopic(String keyWord){
	   WordNetWrapper getSynonymWord=new WordNetWrapper();
	   String replySentence=null;
	   
	   // put all the synonym words to the synonymList which we can choose one of them in random.
	   synonymList.addAll(getSynonymWord.getSynonyms(POS.NOUN,keyWord));
	   
	   //Defines respective indexes for the synonym and template, then use template index to 
	   //generate a reply and use synonym index to get a synonym randomly in the synonym list.
	   int indexSynonym=randomGenerator.nextInt(synonymList.size());
	   int indexTemplate=randomGenerator.nextInt(sentenceList.size());
	    while(sentenceList.get(indexTemplate).getSentenceType()!="reply")
	    {
	       indexTemplate=randomGenerator.nextInt(sentenceList.size());
	   }
	   String getSentenceTemplate=sentenceList.get(indexTemplate).getTemplate();
	   
	   //Replaces all the VERB, NOUN, Adjective with their random synonym
	   getSentenceTemplate=getSentenceTemplate.replace("NOUN",synonymList.get(indexSynonym));
	   getSentenceTemplate=getSentenceTemplate.replace("VERB",getSynonymWord.getVerbAtRandom());
	   getSentenceTemplate=getSentenceTemplate.replace("Adjective",getSynonymWord.getAdjectiveAtRandom());
	   
	   //Replaces the delimiter with blank character
	   getSentenceTemplate=getSentenceTemplate.replace("||"," ");
	   replySentence=getSentenceTemplate;
	   return replySentence;
	   }

	/**
	 * Generate a reply to the specified remark. The reply is related to the 
     * input remark in the vague sense that it contains a word relating to one 
     * of the words in the input
     * 
	 * @param remark The remark which must be responded to
     * 
	 * @return A string containing a response to the specified remark
	 */    
	public String generateReply(String remark) {
	   
	    //generate a random which is 0 or 1 to choose the method of generating reply
	    int randomNumber=(int)(Math.random()*10);
	    int replyChoice=randomNumber%2;
	    String reply=null;
	    String keyWord=null;
	    
	    //Replies with different metods findKeyWord or keyWordMatch according to the
	    //the replyChoice
	    if (replyChoice==0){
	        keyWord=findKeyWord(remark);
	        reply=expandTemplateTopic(keyWord);
	        return reply;
	       }
	       
	       reply=keyWordMatch(remark);
		   return reply;
	}
    
   

}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -