我想知道是否有可能獲取檔案的文本內容并將其轉換為字串或陣列,以便從中獲取隨機單詞。
我必須在 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>
uj5u.com熱心網友回復:
您可以提示用戶輸入號碼。
您可以在回傳的文本上運行正則運算式匹配來查找 words。這將回傳一個陣列。
然后,您可以使用從零到提示數字的回圈,從陣列中拼接出隨機單詞并記錄下來。請注意,
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>
uj5u.com熱心網友回復:
假設你正在閱讀一個文本檔案,那么
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))];
長話短說,你的問題沒有明確的答案,但這里有一些關于如何繼續前進的提示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/348454.html
標籤:javascript 文件 随机的
