gpt4 book ai didi

javascript - 计算 char(array) 在 JavaScript 中句子(数组)中的出现次数

转载 作者:行者123 更新时间:2023-11-29 17:22:52 24 4
gpt4 key购买 nike

我们如何找到并计算以下句子中出现的次数?

sentences = [
'black im yello'
'green black and white'
'green green green green green greenana'
'i have no color'
]

find_char = [
'green',
'black',
'white'
]

应该返回

output = {
'sentence 1' : 1 // just black
'sentence 2' : 3 // green black white
'sentence 3' : 6 // 5 green and green in 'green'ana
'sentence 4' : 0
}

这是我当前的代码

var output = {};

for (var i = sentences.length - 1; i >= 0; i--) {
var output_tmp = {};
var occurance = 0;
for (x = 0; x < find_char.length; x++) {
j = 0;
output_tmp[find_char[x]] = 0;
// search if sentences then -1, if > -1 then there is a match
while ((j = sentences[i].indexOf(find_char[x], j)) > -1) {
output_tmp[find_char[x]]++;
j++
}
occurance += output_tmp[find_char[x]];
}
output[i] = { 'sentence_no': i, 'occurance' : occurance};
}

有更好的方法吗?

最佳答案

将所有单词组合成一个正则表达式并将其应用于每个句子:

sentences = [
'black im yello',
'green black and white',
'green green green green green greenana',
'i have no color'
]

words = [
'green',
'black',
'white'
]

re = new RegExp(words.join('|'), 'gi')

counts = sentences.map(function(sent) {
return (sent.match(re) || []).length
})

这在控制台中打印:

[1, 3, 6, 0]

关于javascript - 计算 char(array) 在 JavaScript 中句子(数组)中的出现次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11460639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com