如果我有两个类似的字符串
s1 = "This is a foo bar sentence ."
s2 = "This sentence is similar to a foo bar sentence ."
我想把字符串拆分成这种格式
x1 = ["This":1,"is":1,"a":1,"bar":1,"sentence":1,"foo":1]
x2 = ["This":1,"is":1,"a":1,"bar":1,"sentence":2,"similar":1,"to":1,"foo":1]
它将字符串单词拆分并计数,形成一对,其中每个字符串表示一个单词,数字表示该单词在字符串中的计数。
删除标点符号,规范化空白,小写,在空格处拆分,使用循环计数索引对象中的单词出现次数。
function countWords(sentence) {
var index = {},
words = sentence
.replace(/[.,?!;()"'-]/g, " ")
.replace(/s+/g, " ")
.toLowerCase()
.split(" ");
words.forEach(function (word) {
if (!(index.hasOwnProperty(word))) {
index[word] = 0;
}
index[word]++;
});
return index;
}
或者,在ES6箭头功能样式中:
const countWords = sentence => sentence
.replace(/[.,?!;()"'-]/g, " ")
.replace(/s+/g, " ")
.toLowerCase()
.split(" ")
.reduce((index, word) => {
if (!(index.hasOwnProperty(word))) index[word] = 0;
index[word]++;
return index;
}, {});