我有一个聊天机器人的矩阵,我用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文件中整数而不是字符串吗?对不起,如果这是一个非常明显的问题......我花了一个小时试图弄清楚如何做到这一点。谢谢你的帮助:))
答案 0 :(得分:1)
您可以在JSON中使用数字和字符串。但对于您的情况,外部类型应为array
而不是object
:
[
{
"input":[""],
"output":["shut up","i dont care","stop talking"]
},
{
"input":["hi","hello","howdy","hey"],
"output":["hi","hello","hey"]
},
{
"input":["how are you", "how r u", "how r you", "how are u"],
"output":["good","doing well"]
}
]
也就是说,JSON不是一个很好的搜索格式。它意味着在程序之间交换数据的简单方法。你想要一个&#34;数据库&#34;代替。
所以你的方法是将文本读入内存数据库&#34; (或数据结构)运行良好,除非你有很多文本。当发生这种情况时,您应该尝试一个简单的数据库,如H2。它甚至支持fulltext search。
答案 1 :(得分:0)