提问者:小点点

检查字符串数组中出现哪些关键字(10k个字)的最有效方法?


我有几个由100个字符串组成的数组,其中包含我使用FETCH检索到的注释。(称为comments)和另一个包含10,000个关键字的数组。(称为关键字)

对于数组中的每个注释,我要检查它包含哪些关键字。(我需要知道它包含的所有关键字,但不需要知道它出现的次数)

最快的方法是什么?

我尝试过foreach在彼此之间循环:

keywords.forEach(word => {
    comments.forEach(comment => {
       if(comment.includes(word)) //call a function
    }
})

以及之间的循环:

for(i = 0; i < keywords.length; i++) {
    for(j = 0; j < comments.length; j++){
         if(comments[j].includes(keywords[i])) //call a function
    }
}

对于这两个,我都尝试过切换内部循环和外部循环。

我还尝试使用关键字构建正则表达式,并使用matchallfor..of循环进行匹配。

keywords.forEach(word => regex = regex + `(^|\\b)${word}(\\b|$)|`)
comments.forEach(comment => {
    const matches = comment.matchAll(regex)
    for (const match of matches){
       //call a function
    }
})

这些都在我最初测试的10个关键字的时候起作用,但是很明显,对于10,000个关键字,这将花费更长的时间。最有效的方法是什么?

这对我来说都是很新的,所以有可能我错过了一些明显的东西!

谢谢


共1个答案

匿名用户

请尝试使用。我已经在关键字数组中创建了一个。现在,对于注释数组中的每个单词,我都可以在中查找它是否包含该单词。

null

const keywords = ["java", "golang", "python", "ruby"];

const comments = ["I love java", "Golang is by google", "Python bit me hard"];

const hash = new Set(keywords.map((k) => k.toLowerCase()));

const test = (w) => console.log(w);

comments.forEach((c) =>
  c.split(" ").forEach((w) => hash.has(w.toLowerCase()) && test(w))
);