【发布时间】:2014-10-07 04:54:18
【问题描述】:
我有一个我用 Java 制作的聊天机器人的矩阵作为响应的知识库:
String[][] knowledgeBase={
{"hi","hello","howdy","hey"},//input 1; if you user inputs any of these,
{"hi","hello","hey"},//output 1; randomly choose between these as a response
{"how are you", "how r u", "how r you", "how are u"},//input 2; if you user inputs any of these,
{"good","doing well"},//output 2; randomly choose between these as a response
{"shut up","i dont care","stop talking"}//if input was in neither array, use one of these as a response
当我在 java 文件中有矩阵时,这可以正常工作。我制作了一个类似于矩阵的 JSON 文件(我是 JSON 新手,所以不太确定格式是否正确):
{
"0":{
"input":[""]
"output":["shut up","i dont care","stop talking"]
}
"1":{
"input":["hi","hello","howdy","hey"]
"output":["hi","hello","hey"]
}
"2":{
"input":["how are you", "how r u", "how r you", "how are u"]
"output":["good","doing well"]
}
}
这是我通过矩阵寻找输入的精确匹配的代码:
public void actionPerformed(ActionEvent e){
//get the user input
String quote=input.getText();
input.setText("");
if(!quote.equals("")){
addText("You:\t"+quote);
quote.trim();
while(quote.charAt(quote.length()-1)=='!' || quote.charAt(quote.length()-1)=='.' || quote.charAt(quote.length()-1)=='?'){
quote=quote.substring(0,quote.length()-1);
}
quote.trim();
byte response=0;
int j=0;
//check the knowledgeBase for a match or change topic
while(response==0){
//if a match is found, reply with the answer
if(inArray(quote.toLowerCase(),knowledgeBase[j*2])){
response=2;
int r=(int)Math.floor(Math.random()*knowledgeBase[(j*2)+1].length);
addText("\nPollockoraptor:\t"+knowledgeBase[(j*2)+1][r]);
}
j++;
//if a match is not found, go to change topic
if(j*2==knowledgeBase.length-1 && response==0){
response=1;
}
}
//change topic if bot is lost
if(response==1){
int r=(int)Math.floor(Math.random()*knowledgeBase[knowledgeBase.length-1].length);
addText("\nPollockoraptor:\t"+knowledgeBase[knowledgeBase.length-1][r]);
}
addText("\n");
}
}
public boolean inArray(String in,String[] str){
boolean match=false;
//look for an exact match
for(int i=0;i<str.length;i++){
if(str[i].equals(in)){
match=true;
}
}
return match;
}
如何搜索具有类似功能的 JSON 文件?我还可以将 JSON 文件中的数字设为整数而不是字符串吗?对不起,如果这是一个非常明显的问题......我花了过去一个小时试图弄清楚如何做到这一点。谢谢你的帮助:)
【问题讨论】:
-
看看this post是否有帮助。