繁体   English   中英

如何使用vanilla Javascript将文件内容放入数组中?

[英]How to put contents of a file into an array using vanilla Javascript?

我想知道是否有可能获取文件的文本内容并将其转换为字符串或数组,以便我可以从中获取随机单词。

我必须在 Javascript 中解决以下编码挑战:

**

从文本中随机显示单词的程序。

1.) 读取一个内容较多的文本文件,随机输出一定数量的单词

例子:

*输入您想要的字数:5

输出:任何接受都应该和甚至*

**

我设法编写了一个在页面上显示文本的代码,但我想不出一个解决方案来获取内容并从中获取随机单词。

 <!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>

  1. 您可以提示用户输入号码。

  2. 您可以在返回的文本上运行正则表达式匹配来查找 words 这将返回一个数组。

  3. 然后,您可以使用从零到提示数字的循环,从数组中拼接出随机单词并记录下来。 请注意, splice返回一个数组,因此您需要访问第一个元素。

 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>

假设你正在阅读一个文本文件,那么

fr.onload=function()
{
 let text  = fr.result;
 let lines = text.split("\r\n");       
}

将文件分成几行。 现在你可以从文件中随机选择一行

let randomline = lines[Math.floor((Math.random() * lines.length))];

但是,当然,如何将文件“切割”成碎片取决于您。 想要分割,比如说,空格?

let words      = text.split(" ");
let randomword = words[Math.floor((Math.random() * words.length))];

长话短说,你的问题没有明确的答案,但这里有一些关于如何继续前进的提示。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM