我试图从字符串中删除停用词的列表。该列表使用$ .get在下面的第3行加载。 如果我尝试在$ .get函数内部使用console.log(stop_words),我可以检索数据。但是它们不会以某种方式添加到数组stop_words中,以便我可以使用$ .get函数之外的数据。JavaScript加载txt单词列表将不会填充数组
注:下面的代码工作正常,如果我直接在原型中声明数组的值。
如何以这种方式将数据分配给stop_words数组,以便在$ .get函数之外使用它?
String.prototype.removeStopWords = function() {
var stop_words = [];
$.get('rsc/stopord.txt', function(data) {
stop_words = data.split('\n');
});
var x;
var y;
var word;
var stop_word;
var regex_str;
var regex;
var cleansed_string = this.valueOf();
// Split out all the individual words in the phrase
words = cleansed_string.match(/[^\s]+|\s+[^\s+]$/g)
// Review all the words
for(x=0; x < words.length; x++) {
// For each word, check all the stop words
for(y=0; y < stop_words.length; y++) {
// Get the current word
word = words[x].replace(/\s+|[^a-z]+/ig, ""); // Trim the word and remove non-alpha
// Get the stop word
stop_word = stop_words[y];
// If the word matches the stop word, remove it from the keywords
if(word.toLowerCase() == stop_word) {
// Build the regex
regex_str = "^\\s*"+stop_word+"\\s*$"; // Only word
regex_str += "|^\\s*"+stop_word+"\\s+"; // First word
regex_str += "|\\s+"+stop_word+"\\s*$"; // Last word
regex_str += "|\\s+"+stop_word+"\\s+"; // Word somewhere in the middle
regex = new RegExp(regex_str, "ig");
// Remove the word from the keywords
cleansed_string = cleansed_string.replace(regex, " ");
}
}
}
return cleansed_string.replace(/^\s+|\s+$/g, "");
}
function keywordDensity() {
var input = tinyMCE.activeEditor.getContent({format : "text"});
input = input.replace(/(<([^>]+)>)/ig, "").replace(/,/g, "").replace(/-/g, "").replace(/"/g, "").replace(/'/g, "").replace(/\./g, " ");
input = input.toLowerCase();
input = input.removeStopWords();
console.log(input);
var keyword = $("#keyword").html();
var wordCounts = { };
var words = input.split(" ");
words = words.filter(Boolean);
for(var i = 0; i < words.length; i++)
wordCounts["_" + words[i]] = (wordCounts["_" + words[i]] || 0) + 1;
keysSorted = Object.keys(wordCounts).sort(function(a,b){return wordCounts[b]-wordCounts[a]})
for(var i = 0; i < keysSorted.length; i++) {
keysSorted[i] = keysSorted[i].replace(/[_-]/g, "");
}
var regexString = keysSorted[0];
var regex = new RegExp("\\b" + regexString, 'g');
var countMostUsed = input.match(regex, regexString);
console.log(input.match(regex, regexString));
console.log("You use the word " + keysSorted[0] + " " + countMostUsed.length + " times");
}
您的$ get需要onsuccess事件。异步加载。 – Mistergreen
'$ .get()'是**异步**。当HTTP请求完成时,您传入的回调将被调用,但对$ .get()的调用本身立即返回。基本上,你的代码中的大部分工作都应该在回调中完成。 – Pointy
@Mistergreen是正确的,只是为了更清楚一点:代码中的所有内容都能正常工作,问题在于,您的函数并没有等待您的$ .get调用在运行其余代码之前完成,因此您的代码会保留运行并且您的stop_word尚未填充。因此,将您的代码添加到成功回调函数中。 – phobia82