简体   繁体   English

计算两个字符串之间的匹配词数

[英]Count the number of matching words between two strings

Hello I would like to ask some help how I can do this in Jquery您好,我想请教一下如何在 Jquery 中做到这一点

Count the number of matching words (in order) between two strings so I can generate accuracy.计算两个字符串之间匹配单词的数量(按顺序),这样我就可以产生准确性。

// Example
string1 = "The lazy fox jumps over the fence" // (7 words)
string2 = "The lazy dog jumps under a fence yesterday" // (8 words)

Output: 4

Accuracy is (4 correct words/7 words to check) = 57%准确率是(4 个正确词/7 个要检查的词)= 57%

Any idea will be appreciated任何想法将不胜感激

You could split each string to words and match the same words by using filter您可以使用filter将每个字符串split为单词并匹配相同的单词

 function getWords(str) { return str.split(" ").filter(Boolean); } function getMatchedWords(words1, words2) { return words1.filter((word) => words2.includes(word)); } const string1 = "The lazy fox jumps over the fence"; const string2 = "The lazy dog jumps under a fence yesterday"; const words1 = getWords(string1); const words2 = getWords(string2); const matchedWords = getMatchedWords(words1, words2); const ratio = +((100 * matchedWords.length) / words1.length).toPrecision(2); console.log(ratio);

Make sets from strings containing word, position tuples then intersect them via logical conjuction & .从包含word, position元组的字符串中创建集合,然后通过逻辑连接&将它们相交。 Depending on whether or not it should be case sensitive apply toUpperCase operation before.取决于它是否应该区分大小写,之前应用toUpperCase操作。 The result set contains matching words from all strings.结果集包含来自所有字符串的匹配词。

By this way you can test any number of strings for the extinct they match to each other.通过这种方式,您可以测试任意数量的字符串是否相互匹配。

I'm on mobile, writing code is not the case, sorry.我在手机上,写代码不是这样,对不起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM