用于查找单词以句子结尾的最常见字母的功能

时间:2016-11-09 10:12:38

标签: javascript

我试图找到一个句子中大多数单词结尾的字母以及以该字母结尾的所有单词。

这是我的作业,我尝试过分割功能,但它没有帮助和切片功能,但需要很长时间。

var sentence = 'Down by the river there is a man that quiver and shiver, but he needs to deliver a packet that he think is a big racket and a packet of of gum.'

function mostWordsEndsWith (){
    for (var i = 0; i < wordsEndsWith.length; i++) {
        var currentWord = wordsEndWith[i].split('t')
        console.log(currentWord);
    }
 }
 mostWordsEndsWith(sentence);

3 个答案:

答案 0 :(得分:0)

let sentence = 'Down by the river there is a man that quiver and shiver, but he needs to deliver a packet that he think is a big racket and a packet of of gum.';

let words = sentence.match(/(\w+)/g);

let letters = {};

//Create an array of object containing the word and his last latter
words = words.map(function(word) {
  return {
    word: word,
    lastLetter: word.slice(-1)
  }
});

//Add the number of occurence for each letters inside the letters object
words.forEach(function(elem) {
  letters[elem.lastLetter] = letters[elem.lastLetter] || 0;
  letters[elem.lastLetter] ++;
});

//Sort the letters object and take the first one
let mostPresentLetter = Object.keys(letters).sort(function(a, b) {
  return letters[b] - letters[a]
})[0];

//Display the most present letter
console.log("Most present letter : " + mostPresentLetter);
//Display all the letters. map is used to display the word only
console.log("Words : " + words.filter(function(item) {
  return item.lastLetter === mostPresentLetter;
}).map(function(o) {
  return o.word;
}));

答案 1 :(得分:0)

这里有一个非常简单的方法,它与旧的JS

兼容

var sentence = 'Down by the river there is a man that quiver and shiver, but he needs to deliver a packet that he think is a big racket and a packet of of gum.'

var census = {};
var most;

sentence.match(/(\w+)\b/g).forEach(function(word) {
  var last = word.substr(-1);
  most = most || last;
  census[last] = census[last] || [];
  // a word that appears more than once is counted each time
  census[last].push(word);
  if (census[last].length > census[most].length) {
    most = last;
  }
});

//console.log(census);
console.log('most repeated letter was: ' + most + ' (' + census[most].length + ' times)');
console.log('and corresponding words were: ' + census[most]);

答案 2 :(得分:-1)

这是一种方法。请注意,它使用了几个ES6功能,以防兼容性成为问题。

&#13;
&#13;
var sentence = "Down by the river there is a man that quiver"
             + " and shiver, but he needs to deliver a packet"
             + " that he think is a big racket and a packet"
             + " of of gum."

function mostWordsEndsWith (str){
  //index for: letter --> { count, words }
  //this is quite a good object itself, however not yet the
  //desired final result
  let endLetterCount = 
         //get array of words
         str.match(/\b\w+\b/g)
            //add information about last letter.
            //There is no error handling, but looking what was
            //matched before, something must go very wrong
            //for it to not match.
            .map((w) => ({
              word: w,
              last: w.match(/(\w)(?:[^\w]|$)/)[1]
            }))
            //create index
            .reduce((p, c) => {
              if (p.hasOwnProperty(c.last)) {
                p[c.last].count++;
                p[c.last].words.push(c.word);
              } else p[c.last] = { count: 1, words: [c.word] };
              return p;
            },
            //ugly, hi javascript...
            //There are lengthy discussions on why objects
            //dont per default work similar to this, not too
            //relevant for this question.
            {
              [Symbol.iterator]: function*(){
                //Here we know exactly what the object is,
                //so issues regarding "own property" are
                //non-existant
                for (prop in this)
                  yield { key: prop, value: this[prop] };
              }
            });
  
  //get the letter with the highest count
  let highestCount = [...endLetterCount].reduce(
    (p, c) => c.value.count > p.value.count ? c : p
  );
  
  //return some nice output format, whatever is wanted.
  return `Letter "${highestCount.key}" occurred most, `
       + `${highestCount.value.count} times: `
       + `${highestCount.value.words}.`;
}

console.log(mostWordsEndsWith(sentence));
&#13;
&#13;
&#13;