2

我试图从一堆段落中提取两个句子,但我被卡住了......基本上,这些段落看起来像这样:

<p class="some_paragraph">This is a sentence. Here comes another sentence. A third sentence.</p>
<p class="some_paragraph">Another sentence here. Interesting information. Very interesting.</p>
<p class="some_paragraph">This is a sentence. Here comes another sentence. A third sentence.</p>

我需要做的是,在这三个段落的所有 9 个句子中找到两个“最短”的句子。必须将两个提取的句子放入以下范围:

<span class="span1">Shortest sentence comes here</span>
<span class="span2">Second shortest sentence comes here</span>

我怎么做?

4

3 回答 3

3
var snt = [];
$('.some_paragraph').each(function() {
    var text = $(this).text();
    text.replace(/[A-Z][^.]+\./g, function(s) {
        if (snt.length < 2) {
            snt.push(s);
        }
        else {
           snt[+(snt[0].length <= snt[1].length)] = s;
        }
    });
});

console.log(snt); // outputs the two shortest sentences

/* creating two span with shortest sentences */
snt.map(function(el, i) {
   $('<span />', { class: "span" + (i+1), text: el }).appendTo($('body')); 
});


/**
 * Result:
 *  
 * <span class="span1">Very interesting.</span>
 * <span class="span2">A third sentence.</span>
 */

小提琴示例:http: //jsfiddle.net/4La9y/2/

为了清楚起见,这个 critic 声明snt[+(snt[0].length <= snt[1].length)] = s;意味着如果我已经用两个句子填充了数组,那么你找到的下一个将被存储在snt[0]ifsnt[1]是最短的地方,反之亦然

于 2012-06-01T08:52:20.713 回答
2
//First grab all text

var t = $('.some_paragraph').text();
var sentences = t.split('.');
sentences.sort(function(a, b) {
    return a.length - b.length;
});
//sortest sentence
$('.span1').text(sentences[1]);
$('.span2').text(sentences[2]);
于 2012-06-01T08:48:57.380 回答
0
var smallest = 0;
            var smaller = 0;
            var bigger = 0;
            var smallest_sen;
            var smaller_sen;

            $('p.some_paragraph').each(function(){
                plength = $(this).text().length;
                if(smallest == 0){
                smallest = plength;
                smallest_sen = $(this).text();
                }else if(smallest > plength){
                    smaller_sen = smallest_sen;
                    smaller = smallest;
                    smallest = plength;
                    smallest_sen = $(this).text();
                }
            });
            alert(smallest_sen);
            alert(smaller_sen);
于 2012-06-01T08:57:50.147 回答