计算长字符串中每个句子的单词,jquery

时间:2016-02-21 03:09:58

标签: javascript jquery arrays

我试图用长字符串计算每个句子中的单词。我得到的只是句子的数量。我在C#和Ruby中找到了一些解决方案,但它们不适合我: - ))

我是java-script的新手。任何帮助非常感谢。以下代码:

输出结果如下:

单词:1发送:1 单词:0 in sent:2 单词:1 in sent:3 单词:1 in sent:4 单词:1发送:5 单词:1 in sent:6

字计数器没有增加!最有可能的是它很简单。 提前谢谢。

var text1 = $('#textarea1').val();   
var gaps = [];
var wordsC = 0;
var wordsTot = 0;
var tempC = 0;
var sents = text1.split('.');    

for (var elem in sents)
{
    tempC += 1;

    wordsC = elem.split(" ").length;
    wordsTot += wordsC;

    if (tempC == 2) {
        wordsC -= 1;
        wordsTot -= 1;
    }

    document.write("<br />Words:  " + wordsC + " |in sent: " + tempC + "  sent");
};

document.write("<br />words total :    " + wordsTot + "<br />" );

2 个答案:

答案 0 :(得分:1)

您不应该使用for...in枚举数组。 text1.split('.');正在生成一个数组,您尝试使用for...in进行枚举。在elem的每次迭代中for...in的值是作为字符串的数组索引之一(&#39; 0&#39;在第一次迭代中,&#39; 1&#39;在第二个等等)。您甚至会最终获得一些Array原型方法以及原型更改的其他内容。

对于ES6之前的环境,请尝试:

for (var i = 0; i < sents.length; i++)
{
    tempC += 1;

    wordsC = sents[i].split(" ").length;
    wordsTot += wordsC;

    if (tempC == 2) {
        wordsC -= 1;
        wordsTot -= 1;
    }

    document.write("<br />Words:  " + wordsC + " |in sent: " + tempC + "  sent");
}

ES6引入了一个for...of构造,可以完成您尝试做的事情:

for (let elem of sents)
{
    tempC += 1;

    wordsC = elem.split(" ").length;
    wordsTot += wordsC;

    if (tempC == 2) {
        wordsC -= 1;
        wordsTot -= 1;
    }

    document.write("<br />Words:  " + wordsC + " |in sent: " + tempC + "  sent");
};

答案 1 :(得分:1)

var str = "There are five words here. I like turtles a lot. This is five words long. Yep.";
var split = str.split(".");
var amountOfSentences = str.charAt(str.length - 1) == "." ? split.length : split.length + 1;
var total = 0;

for (i = 0; i < amountOfSentences - 1; i++) {
    $("body").append("Sentence " + (i + 1) + ": ");
    for (j = 0; j < split[i].split(" ").length - 1; j++) {
        total++;
    }
    if (i == 0) total++;
    $("body").append(" " + total + "<br />");
    total = 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

  

这里有五个字。我非常喜欢海龟。这是五个字长。是的。

这将输出:

  句子1:5
  句2:5
  句3:5
  句子4:1

句子的结尾可以以点结尾,不重要(在var amountOfSentences中考虑)。这对你有用吗?

相关问题