如何获取页面上使用的所有单词的数组 [英] How to get an Array of all words used on a page
问题描述
所以我正在尝试获取我的网页中使用的所有单词的数组。
So I'm trying to get an array of all the words used in my web page.
应该很简单,对吗?
我遇到的问题是 $(body)。text()。split()
返回一个数组所在的单词在一个元素的开头和另一个元素的结尾作为一个元素连接。
The problem I run into is that $("body").text().split(" ")
returns an array where the words at the beginning of one element and end of another are joined as one.
ie:
<div id="1">Hello
<div id="2">World</div>
</div>
返回 [HelloWorld]
当我希望它返回 [你好,世界]
。
我也尝试过:
wordArr = [];
function getText(target)
{
if($(this).children())
{
$(this).children(function(){getText(this)});
}
else
{
var testArr = $(this).text().split(" ");
for(var i =0; i < testArr.length; i++)
wordArr.push(testArr[i]);
}
}
getText("body");
但是 $(节点).children()
对于存在的DOM中的任何节点来说都是真实的,所以这不起作用。
but $(node).children()
is truthy for any node in the DOM that exists, so that didn't work.
我确定我错过了一些明显的东西,所以我很感激额外的一双眼睛。
I'm sure I'm missing something obvious, so I'd appreciate an extra set of eyes.
对于它的价值,我不需要唯一的单词,只需要文档正文中的每个单词作为数组中的元素。我试图用它来生成上下文和词汇共现与另一组词,所以重复一个给定词的上下文重要性。
For what it's worth, I don't need unique words, just every word in the body of the document as an element in the array. I'm trying to use it to generate context and lexical co-occurrence with another set of words, so duplicates just up the contextual importance of a given word.
谢谢你提出任何想法。
请参阅小提琴
推荐答案
这样的事情怎么样?
var res = $('body *').contents().map(function () {
if (this.nodeType == 3 && this.nodeValue.trim() != "")
return this.nodeValue.trim();
}).get().join(" ");
console.log(res);
演示
获取单词数组:
Demo
Get the array of words:
var res = $('body *').contents().map(function () {
if (this.nodeType == 3 && this.nodeValue.trim() != "") //check for nodetype text and ignore empty text nodes
return this.nodeValue.trim().split(/\W+/); //split the nodevalue to get words.
}).get(); //get the array of words.
console.log(res);
这篇关于如何获取页面上使用的所有单词的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!