This code makes summaries from larger texts.
I have searched around for an algorithm and found the following:
Associate words with their grammatical counterparts. (e.g. "city" and "cities")
Calculate the occurrence of each word in the text.
Assign each word with points depending on their popularity.
Detect which periods represent the end of a sentence. (e.g "Mr." does not).
Split up the text into individual sentences.
Rank sentences by the sum of their words' points.
Return X of the most highly ranked sentences in chronological order.
Based on this, I've written some code.
I'm fairly new to javascript so basically I'd really appreciate tips on the following:
- Possible improvements on algorithm
- Coding style
summary.js
var stopwords = require('stopwords').english; //https://github.com/huned/node-stopwords
var natural = require('natural'); //https://github.com/NaturalNode/natural
function Summary(text) {
if (typeof text !== 'string') throw new Error("Argument must be a string");
this.text = text
this.sentences = [];
this.sentencesScore = {};
this.wordPoints = {};
}
Summary.prototype.wordFrequency = function () {
return this.text.split(/\s+/)
.filter(word => { return stopwords.indexOf(word.toLowerCase()) < 0; })
.map(word => { return natural.PorterStemmer.stem(word); })
.reduce(function(map, word) {
map[word] = (map[word] || 0) + 1;
return map;
}, this.wordPoints);
}
Summary.prototype.splitTextIntoSentences = function () {
this.sentences = this.text.replace(/([.?!])\s*(?=[A-Z])/g, "$1|").split("|")
return this.sentences;
}
Summary.prototype.rankSentences = function () {
for(var i = 0, count = 0; i < this.sentences.length; i++) {
var sentence = this.sentences[i];
sentence.split(/\s+/)
.filter(word => { return stopwords.indexOf(word.toLowerCase()) < 0; })
.map(word => { return natural.PorterStemmer.stem(word); })
.forEach(word => {
count += this.wordPoints[word] || 0;
});
this.sentencesScore[sentence] = count;
count = 0;
}
}
Summary.prototype.printMostValuable = function() {
var sortable = [];
for (var sentence in this.sentencesScore) {
sortable.push([sentence, this.sentencesScore[sentence]])
}
sortable.sort(function(a, b) {return b[1] - a[1]});
console.log(sortable);
}
var text = "The political future of Brazilian President Dilma Rousseff hangs in the balance as lawmakers consider a request to impeach her and she waits to hear whether the country's Supreme Federal Court will deal her a significant setback.The court is considering whether to allow Rousseff's appointment of ex-President Luiz Inacio Lula da Silva to her Cabinet, a move that would help shield him from prosecution while he is under investigation in a wide-ranging graft probe. The court made no decision when it reconvened Wednesday, but it was scheduled to meet again Thursday.Rousseff is also facing maneuvers in the National Congress to impeach her over allegations that she tried to hide a budget shortfall ahead of elections in 2014.Hundreds of government supporters carrying red banners bearing the logo of her ruling Workers' Party gathered on the lawn Thursday before the Congress in the capital, Brasilia, where the impeachment commission was hearing the testimony of government witnesses.Supporters plan to stage demonstrations in five states across the country Thursday in solidarity with the embattled President."
var s = new Summary(text);
s.wordFrequency();
s.splitTextIntoSentences();
s.rankSentences();
s.printMostValuable();
The output from this, is an array
containing the sentences + the calculated score (most important):
[ [ 'Hundreds of government supporters carrying red banners bearing the logo of her ruling Workers\' Party gathered on the lawn Thursday before the Congress in the capital, Brasilia, where the impeachment commission was hearing the testimony of government witnesses.',
28 ],
[ 'The political future of Brazilian President Dilma Rousseff hangs in the balance as lawmakers consider a request to impeach her and she waits to hear whether the country\'s Supreme Federal Court will deal her a significant setback.',
24 ],
[ 'The court is considering whether to allow Rousseff\'s appointment of ex-President Luiz Inacio Lula da Silva to her Cabinet, a move that would help shield him from prosecution while he is under investigation in a wide-ranging graft probe.',
19 ],
[ 'Rousseff is also facing maneuvers in the National Congress to impeach her over allegations that she tried to hide a budget shortfall ahead of elections in 2014.',
14 ],
[ 'Supporters plan to stage demonstrations in five states across the country Thursday in solidarity with the embattled President.',
11 ],
[ 'The court made no decision when it reconvened Wednesday, but it was scheduled to meet again Thursday.',
8 ] ]