gpt4 book ai didi

javascript - 从数组中删除几个单词 - Javascript

转载 作者:行者123 更新时间:2023-11-28 20:57:47 26 4
gpt4 key购买 nike

我有一个单词数组,需要按频率排序。在此之前,我需要删除诸如“the”、“it”等单词(实际上少于三个字母的任何单词),以及所有数字和任何以 # 开头的单词(单词数组是从Twitter,尽管下面的示例只是维基百科的随机段落)。

我可以删除一个单词,但一直在疯狂地尝试删除多个单词或一个范围。有什么建议么?谢谢!

http://jsfiddle.net/9NzAC/6/

HTML:

<div id="text" style="background-color:Teal;position:absolute;left:100px;top:10px;height:500px;width:500px;">
Phrenology is a pseudoscience primarily focused on measurements of the human skull, based on the concept that the brain is the organ of the mind, and that certain brain areas have localized, specific functions or modules. The distinguishing feature of phrenology is the idea that the sizes of brain areas were meaningful and could be inferred by examining the skull of an individual.
</div>

JS:

//this is the function to remove words
<script type="text/javascript">
function removeA(arr){
var what, a= arguments, L= a.length, ax;
while(L> 1 && arr.length){
what= a[--L];
while((ax= arr.indexOf(what))!= -1){
arr.splice(ax, 1);
}
}
return arr;
}
</script>

//and this does the sorting & counting
<script type="text/javascript">
var getMostFrequentWords = function(words) {
var freq={}, freqArr=[], i;

// Map each word to its frequency in "freq".
for (i=0; i<words.length; i++) {
freq[words[i]] = (freq[words[i]]||0) + 1;
}

// Sort from most to least frequent.
for (i in freq) freqArr.push([i, freq[i]]);
return freqArr.sort(function(a,b) { return b[1] - a[1]; });
};

var words = $('#text').get(0).innerText.split(/\s+/);

//Remove articles & words we don't care about.
var badWords = "the";
removeA(words,badWords);
var mostUsed = getMostFrequentWords(words);
alert(words);

</script>

最佳答案

不必从原始数组中删除,只需 push 到一个新数组,这样更简单,并且会使您的代码更短、更具可读性。

var words = ['the', 'it', '12', '#twit', 'aloha', 'hello', 'bye']
var filteredWords = []

for (var i = 0, l = words.length, w; i < l; i++) {
w = words[i]
if (!/^(#|\d+)/.test(w) && w.length > 3)
filteredWords.push(w)
}

console.log(filteredWords) // ['aloha', 'hello']

演示: http://jsfiddle.net/VcfvU/

关于javascript - 从数组中删除几个单词 - Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11752143/

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