我有2个阵列:
sentence []
keywords []
例如sentence []
:
sentence [0] = "my car is blue"
sentence [1] = "the dog is sleeping"
sentence [2] = "I am in the kitchen"
sentence [3] = "How are you"
和keywords []
:
keywords [0] = "my"
keywords [1] = " "
keywords [2] = "car"
keywords [3] = " "
keywords [4] = "is"
keywords [5] = " "
keywords [6] = "blue"
keywords [7] = "gghcxfkjc"
keywords [8] = "532jj"
keywords [9] = "How"
keywords [10] = " "
keywords [11] = "are"
keywords [12] = " "
keywords [13] = "you"
keywords [14] = " "
keywords [15] = "tech"
因此,例如,我需要检测“我的车是蓝色的”和“你好吗”是否在keywords
数组中。
请注意,关键字[]遵循句子的顺序。
如何在信息上进行比较和检测?
[编辑]我需要知道关键字[] 中匹配的每个单词的索引 例如,第一句为0,1,2,3,4,另一句为9,10,11,12,13。
答案 0 :(得分:2)
只需join
个关键字并在结果字符串中查找句子:
kw = keywords.join("")
sentence.forEach(function(s) {
console.log(s, kw.indexOf(s) >= 0);
});
打印
my car is blue true
the dog is sleeping false
I am in the kitchen false
How are you true
答案 1 :(得分:1)
所以,你想循环遍历sentence
,并检查关键词中是否有任何句子。
这就是诀窍:
// Build a big string of all keywords
var keyWordLine = keywords.join('').toLowerCase(); // "my car is bluegghcxfkjc532jjHow are you tech"
// Loop through all sentences
for(var i = 0; i < sentence; i++){
// Check the current sentence
if(keyWordLine.indexOf(sentence[i].toLowerCase()) !== -1){
// sentence is in the keywords!
}else{
// sentence is not in the keywords!
}
}
现在,您对这些结果的处理取决于您。例如,您可以构建一个仅包含keywords
中出现的句子的数组:
var keywords = ["my", " ", "car", " ", "is", " ", "blue", "gghcxfkjc", "532jj", "How", " ", "are", " ", "you", " ", "tech"],
sentence = ["my car is blue", "the dog is sleeping", "I am in the kitchen", "How are you"],
keyWordLine = keywords.join('').toLowerCase(),
output = [];
for(var i = 0; i < sentence; i++){
if(keyWordLine.indexOf(sentence[i].toLowerCase()) !== -1){
output.push(sentence[i]);
}
}
alert(output);