Après avoir nettoyé la chaîne, vous pouvez faire correspondre les caractères qui ne sont pas des espaces ou les limites des mots.
Voici deux expressions régulières simples permettant de capturer des mots dans une chaîne de caractères :
- Séquence de caractères non-blancs :
/\S+/g
- Caractères valides entre les limites des mots :
/\b[a-z\d]+\b/g
L'exemple ci-dessous montre comment récupérer le nombre de mots d'une chaîne de caractères, en utilisant ces modèles de capture.
/*Redirect console output to HTML.*/document.body.innerHTML='';console.log=function(s){document.body.innerHTML+=s+'\n';};
/*String format.*/String.format||(String.format=function(f){return function(a){return f.replace(/{(\d+)}/g,function(m,n){return"undefined"!=typeof a[n]?a[n]:m})}([].slice.call(arguments,1))});
// ^ IGNORE CODE ABOVE ^
// =================
// Clean and match sub-strings in a string.
function extractSubstr(str, regexp) {
return str.replace(/[^\w\s]|_/g, '')
.replace(/\s+/g, ' ')
.toLowerCase().match(regexp) || [];
}
// Find words by searching for sequences of non-whitespace characters.
function getWordsByNonWhiteSpace(str) {
return extractSubstr(str, /\S+/g);
}
// Find words by searching for valid characters between word-boundaries.
function getWordsByWordBoundaries(str) {
return extractSubstr(str, /\b[a-z\d]+\b/g);
}
// Example of usage.
var edisonQuote = "I have not failed. I've just found 10,000 ways that won't work.";
var words1 = getWordsByNonWhiteSpace(edisonQuote);
var words2 = getWordsByWordBoundaries(edisonQuote);
console.log(String.format('"{0}" - Thomas Edison\n\nWord count via:\n', edisonQuote));
console.log(String.format(' - non-white-space: ({0}) [{1}]', words1.length, words1.join(', ')));
console.log(String.format(' - word-boundaries: ({0}) [{1}]', words2.length, words2.join(', ')));
body { font-family: monospace; white-space: pre; font-size: 11px; }
Trouver des mots uniques
Vous pourriez également créer un mappage de mots pour obtenir des comptes uniques.
function cleanString(str) {
return str.replace(/[^\w\s]|_/g, '')
.replace(/\s+/g, ' ')
.toLowerCase();
}
function extractSubstr(str, regexp) {
return cleanString(str).match(regexp) || [];
}
function getWordsByNonWhiteSpace(str) {
return extractSubstr(str, /\S+/g);
}
function getWordsByWordBoundaries(str) {
return extractSubstr(str, /\b[a-z\d]+\b/g);
}
function wordMap(str) {
return getWordsByWordBoundaries(str).reduce(function(map, word) {
map[word] = (map[word] || 0) + 1;
return map;
}, {});
}
function mapToTuples(map) {
return Object.keys(map).map(function(key) {
return [ key, map[key] ];
});
}
function mapToSortedTuples(map, sortFn, sortOrder) {
return mapToTuples(map).sort(function(a, b) {
return sortFn.call(undefined, a, b, sortOrder);
});
}
function countWords(str) {
return getWordsByWordBoundaries(str).length;
}
function wordFrequency(str) {
return mapToSortedTuples(wordMap(str), function(a, b, order) {
if (b[1] > a[1]) {
return order[1] * -1;
} else if (a[1] > b[1]) {
return order[1] * 1;
} else {
return order[0] * (a[0] < b[0] ? -1 : (a[0] > b[0] ? 1 : 0));
}
}, [1, -1]);
}
function printTuples(tuples) {
return tuples.map(function(tuple) {
return padStr(tuple[0], ' ', 12, 1) + ' -> ' + tuple[1];
}).join('\n');
}
function padStr(str, ch, width, dir) {
return (width <= str.length ? str : padStr(dir < 0 ? ch + str : str + ch, ch, width, dir)).substr(0, width);
}
function toTable(data, headers) {
return $('<table>').append($('<thead>').append($('<tr>').append(headers.map(function(header) {
return $('<th>').html(header);
})))).append($('<tbody>').append(data.map(function(row) {
return $('<tr>').append(row.map(function(cell) {
return $('<td>').html(cell);
}));
})));
}
function addRowsBefore(table, data) {
table.find('tbody').prepend(data.map(function(row) {
return $('<tr>').append(row.map(function(cell) {
return $('<td>').html(cell);
}));
}));
return table;
}
$(function() {
$('#countWordsBtn').on('click', function(e) {
var str = $('#wordsTxtAra').val();
var wordFreq = wordFrequency(str);
var wordCount = countWords(str);
var uniqueWords = wordFreq.length;
var summaryData = [
[ 'TOTAL', wordCount ],
[ 'UNIQUE', uniqueWords ]
];
var table = toTable(wordFreq, ['Word', 'Frequency']);
addRowsBefore(table, summaryData);
$('#wordFreq').html(table);
});
});
table {
border-collapse: collapse;
table-layout: fixed;
width: 200px;
font-family: monospace;
}
thead {
border-bottom: #000 3px double;;
}
table, td, th {
border: #000 1px solid;
}
td, th {
padding: 2px;
width: 100px;
overflow: hidden;
}
textarea, input[type="button"], table {
margin: 4px;
padding: 2px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1>Word Frequency</h1>
<textarea id="wordsTxtAra" cols="60" rows="8">Four score and seven years ago our fathers brought forth on this continent, a new nation, conceived in Liberty, and dedicated to the proposition that all men are created equal.
Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting place for those who here gave their lives that that nation might live. It is altogether fitting and proper that we should do this.
But, in a larger sense, we can not dedicate -- we can not consecrate -- we can not hallow -- this ground. The brave men, living and dead, who struggled here, have consecrated it, far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us -- that from these honored dead we take increased devotion to that cause for which they gave the last full measure of devotion -- that we here highly resolve that these dead shall not have died in vain -- that this nation, under God, shall have a new birth of freedom -- and that government of the people, by the people, for the people, shall not perish from the earth.</textarea><br />
<input type="button" id="countWordsBtn" value="Count Words" />
<div id="wordFreq"></div>