Come calcolare il tempo di lettura stimato di un testo utilizzando una macro ONLYOFFICE
La stima del tempo di lettura è una funzione preziosa negli editor di testo, che consente agli utenti di determinare quanto tempo potrebbe essere necessario per leggere un documento. Uno dei nostri stagisti, Vukasin, ha creato una macro originale ma efficace che calcola il tempo di lettura stimato in ONLYOFFICE Document Editor. In questo articolo, spiegheremo cosa fa ogni funzione e come si combina per fornire una stima accurata del tempo di lettura.
Costruzione della macro
Per prima cosa si recupera l’oggetto documento con il metodo Api.GetDocument():
try {
const document = Api.GetDocument();
Definizione delle costanti
// Constants for reading speed calculations
const WORDS_PER_MINUTE = 238; // Average adult reading speed
const COMPLEX_WORD_LENGTH = 7; // Words with this many chars or more are considered complex
Qui sono definite due costanti:
- WORDS_PER_MINUTE: La velocità media di lettura di un adulto (238 parole al minuto).
- COMPLEX_WORD_LENGTH: Una soglia per determinare se una parola è complessa.
Conteggio delle parole
La funzione countWords divide il testo dato in parole in base agli spazi bianchi e conta il numero di parole non vuote:
function countWords(text) {
if (!text) return 0;
return text.split(/\s+/).filter((word) => word.length > 0).length;
}
Stima della complessità
Per stimare la complessità usiamo la funzione estimatedComplexety:
function estimateComplexity(text) {
if (!text) return 0;
const words = text.split(/\s+/).filter((word) => word.length > 0);
if (words.length === 0) return 0;
const complexWords = words.filter(
(word) => word.length >= COMPLEX_WORD_LENGTH
).length;
return complexWords / words.length;
}
Questa funzione determina la complessità del testo:
- Dividendo il testo in parole.
- Filtrando le parole con meno di 7 caratteri.
- Calcolando il rapporto tra le parole complesse e il numero totale di parole.
Recupero ed elaborazione dei paragrafi
Poi, continuiamo a processare il testo:
const paragraphs = document.GetAllParagraphs();
let totalWords = 0;
let totalText = "";
paragraphs.forEach((paragraph) => {
const text = paragraph.GetText();
totalWords += countWords(text);
totalText += text + " ";
});
In questa sezione eseguiamo le seguenti operazioni:
- Recuperiamo tutti i paragrafi del documento.
- Eseguiamo il loop di ogni paragrafo per estrarre il testo.
- Contiamo le parole in ogni paragrafo e accumuliamo il conteggio totale delle parole.
- Memorizziamo tutto il testo per stimare la complessità.
Regolazione della complessità
In questo caso, il fattore di complessità viene utilizzato per regolare la velocità di lettura. Una maggiore complessità comporta una minore velocità di lettura effettiva:
const complexityFactor = estimateComplexity(totalText);
const complexityAdjustment = 1 - complexityFactor * 0.3;
const effectiveWPM = WORDS_PER_MINUTE * complexityAdjustment;
Calcolo del tempo di lettura
Quindi convertiamo il totale delle parole in minuti e poi in ore:
const readingTimeMinutes = totalWords / effectiveWPM;
const readingTimeHours = readingTimeMinutes / 60;
Formattazione dell’output
Successivamente, formattiamo l’output del tempo di lettura in base al tempo calcolato.
let readingTimeText;
if (readingTimeMinutes < 1) {
readingTimeText = `less than 1 minute`;
} else if (readingTimeMinutes < 60) {
readingTimeText = `${Math.ceil(readingTimeMinutes)} minute${Math.ceil(readingTimeMinutes) !== 1 ? "s" : ""
}`;
} else {
const hours = Math.floor(readingTimeHours);
const remainingMinutes = Math.ceil((readingTimeHours - hours) * 60);
readingTimeText = `${hours} hour${hours !== 1 ? "s" : ""}${remainingMinutes > 0
? ` and ${remainingMinutes} minute${remainingMinutes !== 1 ? "s" : ""
}`
: ""
}`;
}
Inserimento dell’output
Poi inseriamo l’output formattato:
const infoText = `Reading Time: ${readingTimeText} (${totalWords} words at ${Math.round(
effectiveWPM
)} words per minute)`;
const oParagraph = Api.CreateParagraph();
oParagraph.AddText(infoText);
oParagraph.SetBold(true);
oParagraph.SetItalic(true);
oParagraph.SetFontFamily("Arial");
document.InsertContent([oParagraph], 0);
} catch (error) {
console.log("Error: " + error.message);
}
})();
Questa sezione:
- Crea una stringa formattata con i dettagli del tempo di lettura.
- Crea un nuovo oggetto paragrafo e vi aggiunge del testo.
- Applica lo stile (grassetto, corsivo e carattere Arial).
- Inserisce il paragrafo all’inizio del documento.
L’intero codice della macro è il seguente:
(function () {
try {
const document = Api.GetDocument();
// Constants for reading speed calculations
const WORDS_PER_MINUTE = 238; // Average adult reading speed
const COMPLEX_WORD_LENGTH = 7; // Words with this many chars or more are considered complex
function countWords(text) {
if (!text) return 0;
return text.split(/\s+/).filter((word) => word.length > 0).length;
}
function estimateComplexity(text) {
if (!text) return 0;
const words = text.split(/\s+/).filter((word) => word.length > 0);
if (words.length === 0) return 0;
const complexWords = words.filter(
(word) => word.length >= COMPLEX_WORD_LENGTH
).length;
return complexWords / words.length;
}
const paragraphs = document.GetAllParagraphs();
let totalWords = 0;
let totalText = "";
paragraphs.forEach((paragraph) => {
const text = paragraph.GetText();
totalWords += countWords(text);
totalText += text + " ";
});
const complexityFactor = estimateComplexity(totalText);
const complexityAdjustment = 1 - complexityFactor * 0.3;
const effectiveWPM = WORDS_PER_MINUTE * complexityAdjustment;
const readingTimeMinutes = totalWords / effectiveWPM;
const readingTimeHours = readingTimeMinutes / 60;
let readingTimeText;
if (readingTimeMinutes < 1) {
readingTimeText = `less than 1 minute`;
} else if (readingTimeMinutes < 60) {
readingTimeText = `${Math.ceil(readingTimeMinutes)} minute${Math.ceil(readingTimeMinutes) !== 1 ? "s" : ""
}`;
} else {
const hours = Math.floor(readingTimeHours);
const remainingMinutes = Math.ceil((readingTimeHours - hours) * 60);
readingTimeText = `${hours} hour${hours !== 1 ? "s" : ""}${remainingMinutes > 0
? ` and ${remainingMinutes} minute${remainingMinutes !== 1 ? "s" : ""
}`
: ""
}`;
}
const infoText = `Reading Time: ${readingTimeText} (${totalWords} words at ${Math.round(
effectiveWPM
)} words per minute)`;
const oParagraph = Api.CreateParagraph();
oParagraph.AddText(infoText);
oParagraph.SetBold(true);
oParagraph.SetItalic(true);
oParagraph.SetFontFamily("Arial");
document.InsertContent([oParagraph], 0);
} catch (error) {
console.log("Error: " + error.message);
}
})();
Ora eseguiamo la macro e vediamo come funziona!
Questa macro fornisce un modo intelligente per stimare il tempo di lettura in ONLYOFFICE e ci auguriamo che diventi un’utile aggiunta al tuo kit di lavoro. Le macro di ONLYOFFICE sono strumenti versatili che aiutano a migliorare in modo significativo le funzionalità predefinite e a creare script su misura per le tue esigenze. Ti invitiamo a esplorare la nostra libreria di metodi API e a sviluppare le tue macro personali. Se hai domande o idee, non esitare a contattarci! Siamo sempre aperti al feedback e alla collaborazione. Buona fortuna e buon lavoro!
About the macro author
Crea il tuo account ONLYOFFICE gratuito
Visualizza, modifica e collabora su documenti, fogli, diapositive, moduli e file PDF online.