【问题标题】:what is best way to match words from list to words from sentence in javascript?在javascript中将列表中的单词与句子中的单词匹配的最佳方法是什么?
【发布时间】:2020-01-04 01:54:11
【问题描述】:

我有两个句子,我想找到它们共享的所有单词,无论大小写或标点符号如何。 目前这就是我正在做的事情:

    searchWords = sentence1.split(" ");
    var wordList = sentence2.split(" ");
    const matchList = wordList.filter(value => -1 !== searchWords.indexOf(value));

它工作正常,但显然大写和标点符号会导致问题。 我知道我需要在其中加入类似 .match() 的东西,但我不知道如何使用它。我相信这是有人在尚未找到代码之前所做的事情,任何参考也表示赞赏。

谢谢,

最好的

这家伙。

【问题讨论】:

  • 通过转换为小写进行比较,例如 searchWords.toLowerCase().indexOf(value.toLowerCase())

标签: javascript arrays string string-matching


【解决方案1】:

如果您正在寻找任何匹配的单词,您可以将RegExpString.prototype.replace 结合使用,并使用String.prototype.search 与创建的RegExpi 标志来验证匹配允许不区分大小写。

function compare(str1, str2, matches = []) {
     str1.replace(/(\w+)/g, m => str2.search(new RegExp(m, "i")) >= 0 && matches.push(m));
     return matches;
 }
 
 console.log( compare("Hello there this is a test", "Hello Test this is a world") );

如果您正在寻找匹配的特定单词,您可以使用functional compositionsplit 将每个字符串转换为Array,通过可能的matches 过滤每个字符串,然后过滤一个反对对方。

function compare(str1, str2, matchables) {
     let containFilter = (a) => (i) => a.includes(i),
     matchFilter = s => s.toLowerCase().split(" ").filter(containFilter(matchables));
     
    return matchFilter(str1).filter(containFilter( matchFilter(str2) ));
 }
 
 let matchables = ["hello", "test", "world"];
 console.log( compare("Hello there this is a test", "Hi Test this is a world", matchables) );

【讨论】:

  • compare("Chapter 1 test.", "Chapter one test") 第一个例子不能正常工作,只匹配 test
  • @TadewosBellete 感谢您告诉我!我只是在索引检查中使用了> 运算符而不是>=
  • 谢谢老兄!我可以在新的 RegExp(m,'i') 中添加一个表达式以使其忽略标点符号吗?
  • @TadewosBellete 当然。有几种方法可以做到这一点。您可以在搜索前去除这些标点字符的字符串,或者您可以手动调整 RegEx。 \w 等同于 [A-Za-z0-9_] - 因此,如果您想删除下划线作为选项,只需将其更改为 [A-Za-z0-9]+ - 但这完全取决于您的用例。这有帮助吗?
【解决方案2】:

我想你可能想多了。将两个句子都转换为数组并使用 for 循环循环单词是否有效?例如:

var searchWords = sentence1.split(" ");
var wordList = sentence2.toLowerCase().split(" ");
var commonWords = [];
for(var i = 0; i < searchWords.length; i++){
    if(wordList.includes(searchWords[i].toLowerCase())){
        commonWords.push(searchWords[i])
    }
}
console.log(commonWords);

或者它的一些变体。

至于标点符号,您可能可以将.replace(/[^A-Za-z0-9\s]/g,"") 添加到searchWords[i].toLowerCase() 的末尾,如以下答案所述:https://stackoverflow.com/a/33408855/10601203

【讨论】:

  • 是的,哈哈,也许你是对的,工作得很好,但标点符号并没有被忽略。可能不需要它。
  • 我为标点添加了一个编辑。您可以将.replace(/[^A-Za-z0-9\s]/g,"") 添加到searchWords[i].toLowerCase() 的末尾,如以下答案中所述:stackoverflow.com/a/33408855/10601203
猜你喜欢
  • 1970-01-01
  • 2022-06-10
  • 1970-01-01
  • 2023-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-05
  • 1970-01-01
相关资源
最近更新 更多