我正在使用技术堆栈(react + nodejs + mongodb)
制作一个doc doc的文本搜索应用程序。
例如,如果我输入" chicken"在我的搜索栏上,我将在我的结果中写一篇关于鸡肉的文章(例如:今晚最受欢迎的鸡肉餐厅因为鸡肉味道很多,所有员工都失业了)。
文本通常太长而无法显示,我想要做的是获取带有关键字的单词的摘录:"最受欢迎的鸡肉餐厅......关于鸡肉味道......&#34 ; 。
你对功能有什么想法吗?
( keyword + max length in parameter)
。我尝试使用substring
和splice
并进行拆分,但我无法找到最简单的方法。
谢谢!
答案 0 :(得分:0)
我试着搜索关键字,在关键字后面加两个初始单词和两个单词,然后加入" ..."。
var longString = "The most popular chicken's restaurant closed tonight because of lot of complain about chicken taste, all the employee lost their jobs";
var keyword = "chicken";
var allWords = longString.split(" ");
var indices = [];
allWords.forEach((word,index)=>{(word.indexOf(keyword)>=0) ? indices.push(index):""});
var newStrings = indices.map((i)=>{
let temp="";
temp=allWords[i-2]?allWords[i-2]+" ":"";
temp+=allWords[i-1]?allWords[i-1]+" ":"";
temp+=allWords[i];
temp+=allWords[i+1]?" "+allWords[i+1]:"";
temp+=allWords[i+2]?" "+allWords[i+2]:"";
return temp;
})
console.log("..."+newStrings.join("...")+"...");

答案 1 :(得分:0)
您可以使用与您的关键字匹配的正则表达式以及与之前和之后的某些字词,例如像这样:
(?:\w+[\s,;:'".!?]+){0,3}(chicken)(?:[\s,;:'".!?]+\w+){0,3}
这需要一些微调来考虑所有可能的标点符号,以及其他奇怪的语言内容与"单词后面跟空格/逗号等不一致"架构。看看ASCII character classes,可能它们会派上用场。
const test_str = ` The most popular chicken's restaurant closed tonight because of lot of complain about chicken taste, all the employee lost their jobs`;
function mySearchFunc(str, lookup) {
const regex = new RegExp("(?:\\w+[\\s,;:'\".!?]+){0,3}" + lookup + "(?:[\\s,;:'\".!?]+\\w+){0,3}", "gm");
let m;
let result = [];
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
if (m)
//console.log(`Found: ${m}`);
result.push(m[0]);
}
return result.join(' ... ');
}
console.log(mySearchFunc(test_str, "chicken"));