如何使用原生Javascript读取文件内容存入数组并实现随机取词
原生JavaScript实现文本文件读取+随机取词方案
核心实现思路
- 读取文本文件后先对内容做清洗,拆分得到无冗余的单词数组
- 新增用户输入取词数量的交互入口,搭配随机抽取逻辑
- 输出指定数量的随机单词,可配置是否保留原单词大小写、是否允许重复抽取
完整可运行代码
<!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> <style> .control-group { margin: 10px 0; } #result { margin-top: 20px; font-size: 18px; font-weight: 500; color: #2c3e50; } </style> </head> <body> <h1>Random Tweet Generator</h1> <!-- 原文件上传控件 --> <input type="file" name="inputfile" id="inputfile" accept=".txt"> <br> <!-- 新增取词数量控制 --> <div class="control-group"> <label>输入想要获取的单词数量:</label> <input type="number" id="wordCount" min="1" value="5"> <button id="generateBtn" disabled>生成随机单词</button> </div> <!-- 原文本预览区域 --> <h3>原文预览:</h3> <pre id="output"></pre> <!-- 新增结果展示区域 --> <h3>随机抽取结果:</h3> <div id="result"></div> <script> // 存储清洗后的单词数组 let wordArr = []; const inputFile = document.getElementById('inputfile'); const output = document.getElementById('output'); const wordCountInput = document.getElementById('wordCount'); const generateBtn = document.getElementById('generateBtn'); const resultBox = document.getElementById('result'); // 原文件读取逻辑改造 inputFile.addEventListener('change', function() { if (!this.files[0]) return; const fr = new FileReader(); fr.onload = function() { const textContent = fr.result; // 展示原文 output.textContent = textContent; // 清洗文本得到单词数组 wordArr = textContent // 拆分所有空白符(空格、换行、制表符等) .split(/\s+/) // 清洗每个单词的前后标点,保留单词本身 .map(word => word.replace(/^[^a-zA-Z]+|[^a-zA-Z]+$/g, '')) // 过滤空字符串 .filter(word => word.length > 0); // 激活生成按钮 generateBtn.disabled = wordArr.length === 0; } fr.readAsText(this.files[0]); }) // 随机生成逻辑 generateBtn.addEventListener('click', function() { const needCount = Number(wordCountInput.value); // 边界判断 if (wordArr.length < needCount) { resultBox.textContent = `文件总单词量仅${wordArr.length}个,小于要求抽取的${needCount}个,请调整数量`; return; } // 洗牌算法抽取不重复单词 const tempArr = [...wordArr]; const randomWords = []; for (let i = 0; i < needCount; i++) { const randomIndex = Math.floor(Math.random() * tempArr.length); randomWords.push(tempArr.splice(randomIndex, 1)[0]); } // 输出结果,空格分隔 resultBox.textContent = randomWords.join(' '); }) </script> </body> </html>
可调整配置项
- 如果需要统一输出小写/大写,可以在清洗单词环节增加
.toLowerCase()或.toUpperCase()处理 - 如果允许重复抽取单词,可去掉洗牌逻辑,直接每次用
Math.floor(Math.random() * wordArr.length)取索引即可 - 可修改
accept=".txt"限制仅能上传txt格式的文本文件
内容的提问来源于stack exchange,提问作者ninna
相关产品推荐
相关产品推荐

