使用Javascript查找字符串中最常见的单词? [英] Using Javascript to find most common words in string?

查看:109
本文介绍了使用Javascript查找字符串中最常见的单词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一大块文字,我想找出最常用的单词(除了少数,如the,a,and等)。

I have a large block of text, and I would like to find out the most common words being used (except for a few, like "the", "a", "and", etc).

我如何搜索这个文本块中最常用的单词?

How would I go about searching this block of text for its most commonly used words?

推荐答案

你应该将字符串拆分成单词,然后遍历单词并为每个单词增加一个计数器:

You should split the string into words, then loop through the words and increment a counter for each one:

var wordCounts = { };
var words = str.split(/\b/);

for(var i = 0; i < words.length; i++)
    wordCounts["_" + words[i]] = (wordCounts["_" + words[i]] || 0) + 1;

_+ 允许它像构造函数这样的过程词,它们已经是对象的属性。

The "_" + allows it to process words like constructor that are already properties of the object.

你可能想写 words [i] .toLowerCase()计算不区分大小。

You may want to write words[i].toLowerCase() to count case-insensitively.

这篇关于使用Javascript查找字符串中最常见的单词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆