我有一个带句子的数组:
term = ["This is some string","This is another string"];
我希望能够通过单个单词进行拆分,并计算整个term
数组中每个单词的出现次数。
简而言之,我想:
["This is some string", "This is another string"];
结束为:
{
This : 2
is : 2
some : 1
another : 1
string : 2
} //(they would be in alphabetic order)
<小时/> 我是通过
这样做的
term.split([" "]);
分割每个术语数组句子
用它来的话通过测试下面的代码,这似乎适用于大多数情况,但 某些字样,最终计数不正确(我没有得到但是任何错误!)。
是否有任何特殊原因导致下面的代码无法正确输出计数?
代码:
var wordsArray{};
var term = ["This is some string", "This is another string"];
for (var x = 0; x < term.length; x++){
var splitted = term.split([" "]);
for (var i = 0; i < splitted.length; i++) { //i = each splitted string(each word)
var count = 1;
if (splitted[i] in wordsArray){
//Add one to key value in wordarray
wordsArray[splitted[i]]++;
} else {
wordsArray[splitted[i]] = count;
}
}
}
我已经将我的过程简单地放在上面,但作为进一步的背景,每个初始句子字符串来自多个迭代的json文件,这个映射包含 all 所有 json文件的句子。 (我这里没有包含此代码,因为我认为它对问题没有任何影响。)
这会对计数结果产生明显影响吗?
答案 0 :(得分:0)
您需要在术语中对每个元素应用拆分。改变这一行
var splitted = term.split([" "]);
到
var splitted = term[x].split([" "]);
所以整个事情看起来像
var wordsArray = {};
var term = ["This is some string", "This is another string"];
for (var x = 0; x < term.length; x++){
var splitted = term[x].split([" "]);
for (var i = 0; i < splitted.length; i++) { //i = each splitted string(each word)
var count = 1;
if (splitted[i] in wordsArray){
//Add one to key value in wordarray
wordsArray[splitted[i]]++;
} else {
wordsArray[splitted[i]] = count;
}
}
}
console.log(wordsArray)
答案 1 :(得分:0)
执行的jQuery方法如下。
var wordsArray = {};
var term = ["This is some string", "This is another string"];
$.each(term, function (index, value) {
var split = value.split(" ");
$.each(split, function (i, v) {
wordsArray[v] = v.length;
});
});
console.log(wordsArray);
这是一个独特的单词数组,键是单词,值是计数。
输出示例:
Object {This: 4, is: 2, some: 4, string: 6, another: 7}
答案 2 :(得分:0)
正如其他人所说,你的示例代码是错误的:第4行应该是
var splitted = term[x].split([" "]); // term[x]
wordcount错误的原因可能,您似乎只将空格视为分隔符。
示例:
var term = ["This is some string.", "this is \"another\" string?"];
产生
"another": 1
this: 1
This: 1
is: 2
some: 1
string.: 1
string?: 1