如何获取大型网页上的独特词(至少是独特词的样本)?
How to get the unique words on a large webpage (at least a sample of unique words)?
我正在尝试处理非常大页面的可见文本,例如,整个 Orwell's "1984" on this page,但是当我尝试以下操作时,我的 Chrome 控制台似乎崩溃了.
var script = document.createElement('script');
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
var allWords = $(document.body).children(":visible").text().split(' ');
var uniqueWords = allWords.filter(function(elem, i, array){ return array.indexOf(elem) === i });
以上内容使我的 Chrome 选项卡在最后一次操作时变得无响应(我停止获取我输入的新命令的输出至少一分钟)。注意:片段的第一部分只是 attaches JQuery to the page.
您将如何尝试以更快的速度处理如此大的字符串?你认为我应该从 allWords
中随机抽样,只对这个较小的字符串应用过滤功能吗?
chrome 选项卡在最后一行执行后挂起的原因是算法的复杂性。您可以将每个单词添加到 Set
而不是对每个单词调用 .indexOf
var uniqueWords = new Set();
allWords.forEach(function (word) {
uniqueWords.add(word)
});
如果需要ES5版本的相同代码,可以使用helper对象作为数据存储。对象键本质上是唯一的,所以你可以用单词作为键填充空对象,用任何你想要的值填充,然后用 Object.keys
方法
提取单词
var uniqueWordsHash = {};
allWords.reduce(function (hash, word) {
hash[word] = null;
return hash;
}, uniqueWordsHash);
var uniqueWordsArray = Object.keys(uniqueWordsHash);
我正在尝试处理非常大页面的可见文本,例如,整个 Orwell's "1984" on this page,但是当我尝试以下操作时,我的 Chrome 控制台似乎崩溃了.
var script = document.createElement('script');
script.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
document.getElementsByTagName('head')[0].appendChild(script);
var allWords = $(document.body).children(":visible").text().split(' ');
var uniqueWords = allWords.filter(function(elem, i, array){ return array.indexOf(elem) === i });
以上内容使我的 Chrome 选项卡在最后一次操作时变得无响应(我停止获取我输入的新命令的输出至少一分钟)。注意:片段的第一部分只是 attaches JQuery to the page.
您将如何尝试以更快的速度处理如此大的字符串?你认为我应该从 allWords
中随机抽样,只对这个较小的字符串应用过滤功能吗?
chrome 选项卡在最后一行执行后挂起的原因是算法的复杂性。您可以将每个单词添加到 Set
而不是对每个单词调用.indexOf
var uniqueWords = new Set();
allWords.forEach(function (word) {
uniqueWords.add(word)
});
如果需要ES5版本的相同代码,可以使用helper对象作为数据存储。对象键本质上是唯一的,所以你可以用单词作为键填充空对象,用任何你想要的值填充,然后用 Object.keys
方法
var uniqueWordsHash = {};
allWords.reduce(function (hash, word) {
hash[word] = null;
return hash;
}, uniqueWordsHash);
var uniqueWordsArray = Object.keys(uniqueWordsHash);