как исправить ошибку?
Подскажите пожалуйста как исправить эти ошибки. через инпут выбираю тестовый файл книги, и код должен обработать весь текст, но в консоли выдает эти ошибки. с импортом лодаш пробовал писать const _ = require('lodash'); но все равно выдает ошибку
lod.js:2 Uncaught ReferenceError: exports is not defined at lod.js:2 (anonymous) @ lod.js:2 lod.js:14 Uncaught TypeError: Cannot read property 'default' of undefined at FileReader.reader.onload <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>file</title> </head> <body> <input type="file" onchange="show(this)"> <script src="lod.js"></script> </body> </html> import _ from 'lodash'; function show(input) { const file = input.files; for (const el of file) { const reader = new FileReader(); reader.readAsText(el); reader.onload = () => { if (typeof reader.result === 'string') { document.write(`Words: ${reader.result.length}`); } const res = _.words(reader.result, /[-а-яё]{4,}/gim); document.write(`Words: ${res}`); const result = _.flow([ _.countBy, _.toPairs, _.partial(_.orderBy, _, 1, 'desc'), _.partial(_.take, _, 10), ]); document.write(`count: ${result(res)}`); }; } } |
prototip, подключите этот лёутящщ как указано у них в документации ( https://cdn.jsdelivr.net/npm/lodash@.../lodash.min.js ), или например при помощи unpkg ( https://unpkg.com/lodash@4.17.21/lodash.min.js ), или можете скачать этот файл к себе.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>file</title> </head> <body> <input type="file" onchange="show(this)"> <output id="info" style="white-space: pre-line;display: block;"></output> <script src="https://unpkg.com/lodash@4.17.21/lodash.min.js"></script> <script> function show(input) { const file = input.files; let info = document.querySelector("output#info"); for (const el of file) { const reader = new FileReader(); reader.readAsText(el); reader.onload = () => { if (typeof reader.result === 'string') { info.append(`Words: ${reader.result.length}\n`); } const res = _.words(reader.result, /[-а-яё]{4,}/gim); info.append(`Words: ${res.join(", ")}\n`); const result = _.flow([ _.countBy, _.toPairs, _.partial(_.orderBy, _, 1, 'desc'), _.partial(_.take, _, 10), ]); info.append(`count: ${result(res).join(", ")}\n`); }; } } </script> </body> </html> Вместо document.write создайте какой-нибудь элемент и в него вставляйте текст. См. пример выше. |
Malleys,
большое спасибо, очень помогли |
Malleys,
последний вопрос. как сделать вывод слов после обработки текста выглядит так: СУБЪЕКТ,1279, души,578, жизни,514, чтобы,331, которые,307, когда,287, меня,269, время,232, Земле,224, того,204 как мне сделать чтобы выводило как в этой картинке https://ibb.co/1XzmBb2 например слева слова, а справа количество слов: СУБЪЕКТ-------------1279 души-------------578 жизни-------------514 чтобы-------------331 которые-------------307 и т.д <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>file</title> <link rel="stylesheet" href="index.css"> </head> <body> <div> <div id="drop-area"> Drag and drop file here </div> <output id="log-div"></output> </div> <div class="file-read"> <div class="file-input"> <label class="custom-file-upload"> <input type="file" onchange="show(this)"> Upload a file </label> </div> <a href="">Reset</a> </div> <div class="output-info"> <output id="info"></output> </div> <script src="https://unpkg.com/lodash@4.17.21/lodash.min.js"></script> <script> function show(input) { const file = input.files; let info = document.querySelector("output#info"); for (const el of file) { const reader = new FileReader(); reader.readAsText(el); reader.onload = () => { const res = _.words(reader.result, /[-а-яё]{4,}/gim); const result = _.flow([ _.countBy, _.toPairs, _.partial(_.orderBy, _, 1, 'desc'), _.partial(_.take, _, 10), ]); info.append(`${result(res).join(", ")}\n`); }; } } </script> </body> </html> #drop-area { border: 4px dashed gray; padding: 100px; margin-top:10px; text-align: center; font-size: 40px; color: gray; } .file-read{ margin-top:30px; text-align: center; } .file-input{ } .custom-file-upload{ border: 4px solid green; background: green; border-radius: 5px; color: white; padding: 10px 45px; position: absolute; left: 190px; } div.file-input label:hover{ background: #1e6225; color: #ff044c; } a{ text-decoration: none; border: 4px solid green; background: green; border-radius: 5px; color: white; padding: 10px 65px; position: absolute; right: 190px; } a:hover { background: #1e6225; color: #ff044c; } .output-info{ margin-top: 100px; text-align: center; } #info{ white-space: pre-line;display: block; } input[type="file"] { display: none; } |
Цитата:
https://ru.stackoverflow.com/questio...словами |
Цитата:
|
prototip,
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8"> <title>focusout</title> </head> <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script> <table id="out"></table> <script> let input = "Ровно мы две недели и прошло с тех пор, как мейстер Карстар решился на похищение. А именно похищением и называлось то, что он провернул. Родители пропавших студентов и пресса уже покинули территорию Академии Шепота – самого престижного учебного заведения Вельгальда до недавних пор, студенты разъезжались по домам, а я провожала Айрату – свою лучшую подругу – до ворот, когда в небе появился синий дракон.\n" + "\n" + "Без вещей, без фамильяра-защитника, положенного мы ведьме, в чужом мы плаще – он похитил меня прямо у ворот, сцапав своими когтистыми лапами."; let res = _.words(input, /[-а-яё]{4,}/gim); let result = _.flow([ _.countBy, _.toPairs, _.partial(_.orderBy, _, 1, 'desc'), _.partial(_.take, _, 10), ]) let txt = result(res).map(([word, num]) => `<tr><td>${word}<td>${num}`).join(''); out.insertAdjacentHTML('beforeend', txt); </script> </body> </html> |
рони,
точно, как же я сразу не додумался) спасибо |
подскажите, если загружаю файл docx результат не выводится. в чем может быть причина?
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>file</title> <link rel="stylesheet" href="index.css"> </head> <body> <div> <div id="drop-area"> Drag and drop file here </div> </div> <div class="file-read"> <div class="file-input"> <label class="custom-file-upload"> <input type="file" onchange="show(this)"> Upload a file </label> </div> <a href="">Reset</a> </div> <div id="table-div"> <table id="out" width="30%"></table> </div> <script src="https://unpkg.com/lodash@4.17.21/lodash.min.js"></script> <script> function show(input) { const file = input.files[0]; const reader = new FileReader(); reader.readAsText(file, "UTF-8"); reader.onload = () => { const res = _.words(reader.result, /[-а-яё]{4,}/gim); const result = _.flow([ _.countBy, _.toPairs, _.partial(_.orderBy, _, 1, 'desc'), _.partial(_.take, _, 10), ]); let txt = result(res).map(([word, num]) => `<tr><td>${word}<td>${num}`).join(''); let out= document.getElementById('out'); out.insertAdjacentHTML('beforeend', txt); }; } </script> </body> </html> |
Часовой пояс GMT +3, время: 08:46. |