Words to numbers è un’interessante libreria JavaScript che permette di convertire automaticamente stringhe testuali rappresentanti cifre nei numeri corrispondenti. Il livello di precisione nelle procedure per il riconoscimento dei contenuti è particolarmente elevato, tanto che l’applicazione riesce ad individuare stringhe indicanti numeri anche quando le componenti alfabetiche e le cifre sono mischiate tra loro.
L’installazione di Words to numbers prevede l’utilizzo del package manager npm:
npm install words-to-numbers
Una volta attiva in un’applicazione, la libreria agisce in modo diverso a seconda della stringa che viene parsata a runtime, nel caso in cui la stringa passata come argomento sia un numero verrà restituito il valore corrispondente espresso sotto forma di tipo di dato numerico, altrimenti verrà restituita la stringa originale contenente però la conversione in cifre di tutte le istanze numeriche presenti.
Per attivare la libreria è sufficiente ricorrere ad un’importazione:
import wordsToNumbers from 'words-to-numbers';
Fatto questo sarà possibile mettere alla prova le funzionalità di Words to numbers passando ad esso la medesima stringa espressa in modo differente o contenuta in ulteriori stringhe:
import wordsToNumbers from 'words-to-numbers'; wordsToNumbers('one hundred'); //100 wordsToNumbers('one hundred and five'); //105 wordsToNumbers('one hundred and twenty five'); //125 wordsToNumbers('a thousand one hundred and eleven'); //1111 wordsToNumbers('twenty thousand five hundred and sixty nine'); //20569 wordsToNumbers('one-hundred'); //100 wordsToNumbers('one-hundred and five'); //105
E’ possibile utilizzare la libreria per riconoscere più numeri contenuti nella medesima stringa e sono supportate anche le stringhe rappresentanti numeri decimali:
import wordsToNumbers from 'words-to-numbers'; wordsToNumbers('ten point five'); //10.5
Da segnalare anche la possibilità di tradurre delle stringhe che rappresentano numeri ordinali:
import wordsToNumbers from 'words-to-numbers'; wordsToNumbers('first'); //1 wordsToNumbers('second'); //2 wordsToNumbers('fourteenth'); //14 wordsToNumbers('one hundred and ninety ninth'); //199
Non meno interessante il supporto per il Fuzzy Matching che nel caso di stringhe più difficilmente traducibili permette di ottenere la migliore corrispondenza possibile con i valori numerici rappresentati:
import wordsToNumbers from 'words-to-numbers'; wordsToNumbers('won huntred', {fuzzy: true}); //100 wordsToNumbers('too thousant and fiev', {fuzzy: true}); //2005
Utile nei casi in cui le stringhe presentano degli errori, il Fuzzy Matching garantisce naturalmente un livello di accuratezza variabile.
Via Words to numbers