Me gustaría saber si existe la posibilidad de obtener el contenido de texto de un archivo y transformarlo en una cadena o matriz, para poder obtener palabras aleatorias de él.
Tengo que resolver el siguiente desafío de codificación en Javascript:
**
Un programa que muestra aleatoriamente palabras de un texto.
1.) Lea un archivo de texto con mucho contenido y genere aleatoriamente una cierta cantidad de palabras
Ejemplo:
*ingresa cuantas palabras quieres: 5
Salida: cualquier aceptación deberá e INCLUSO*
**
Me las arreglé para escribir un código que muestra un texto en la página, pero no puedo pensar en una solución para obtener el contenido y obtener palabras aleatorias de él.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title>Random Tweet Generator</title> <input type="file" name="inputfile" id="inputfile"> <br> <pre id="output"></pre> <style> </style> </head> <body> <h1>Random Tweet Generator</h1> <script> document.getElementById('inputfile') .addEventListener('change', function() { let fr=new FileReader(); fr.onload=function(){ document.getElementById('output') .textContent=fr.result; } fr.readAsText(this.files[0]); }) </script> </body> </html>Puede solicitar al usuario un número.
Puede ejecutar una coincidencia de expresiones regulares en el texto devuelto que busca palabras . Esto devolverá una matriz.
A continuación, puede utilizar un ciclo desde cero hasta el número solicitado, separando palabras aleatorias de la matriz y registrándolas. Tenga en cuenta que el splice devuelve una matriz, por lo que debe acceder al primer elemento.
const output = document.getElementById('output'); const input = document.getElementById('inputfile'); input.addEventListener('change', handleChange, false); const numberOfWords = +prompt('How many words?'); function randomNumber(max) { return Math.floor(Math.random() * (max - 0) + 0); } function handleChange() { // The regex to match words const regex = /\w(?<!\d)[\w'-]*/g; let fr = new FileReader(); fr.onload = function () { // Produce an array of words in the file const arr = fr.result.match(regex); // From 0 to the numberOfWords // get a random number based on the length of the array // splice a word out and log it for (let i = 0; i < numberOfWords; i++) { const rnd = randomNumber(arr.length); const word = arr.splice(rnd, 1); console.log(word[0].toLowerCase()); } } fr.readAsText(this.files[0]); } <input type="file" name="inputfile" id="inputfile"> <br> <pre id="output"></pre> <h1>Random Tweet Generator</h1>Suponiendo que está leyendo un archivo de texto, entonces
fr.onload=function() { let text = fr.result; let lines = text.split("\r\n"); }dividirá el archivo en líneas. Ahora puede elegir aleatoriamente una línea del archivo
let randomline = lines[Math.floor((Math.random() * lines.length))];Pero, por supuesto, depende de usted cómo "corta" los archivos en pedazos. ¿Quieres dividir por, digamos, espacios?
let words = text.split(" "); let randomword = words[Math.floor((Math.random() * words.length))];Para resumir, no hay una respuesta definitiva a su pregunta, pero aquí hay algunos consejos sobre cómo seguir adelante.