Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Web программирование > JavaScript, Ajax
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 15.06.2023, 19:19   #1
gimes
Пользователь
 
Регистрация: 17.01.2022
Сообщений: 58
Вопрос Прошу подправить скрипт экспертной системы

Человек написал программу (макет для более сложного варианта), только неудобно, что файлы настроек нужно загружать каждый раз из интерфейса. Поправьте пожалуйста код, чтобы автоматически подгружалось.
index.html
Код:
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Рецепты</title>
        <style>
            hr {
             border: none; 
             background-color: black; 
             color: black; 
             height: 2px; 
            }
        </style>
    </head>

    <body>
        <div id="recipe-container">
            <strong>Рецепты</strong>
            <input type="file" id="recipe-selector">
            <p id="recipe-error-check"></p>
        </div>
        <div>
            <strong>Ингредиенты</strong>
            <input type="file" id="ingredient-selector">
            <p id="ingredient-error-check"></p>
        </div>
        <div id="input-container"></div>

        <button id="submit">Обработать</button>
        <button id="clear">Очистить</button>
        <button id="check-all">Выбрать всё</button>

        <p id="answer"></p>

        <script src="main.js"></script>
    </body>

</html>
main.js
Код:
// функция переводит русские слова на латиницу это нужно для создания уникальных id для checkbox-ов 
function rus_to_latin ( str ) {
    
    var ru = {
        'а': 'a', 'б': 'b', 'в': 'v', 'г': 'g', 'д': 'd', 
        'е': 'e', 'ё': 'e', 'ж': 'j', 'з': 'z', 'и': 'i', 
        'к': 'k', 'л': 'l', 'м': 'm', 'н': 'n', 'о': 'o', 
        'п': 'p', 'р': 'r', 'с': 's', 'т': 't', 'у': 'u', 
        'ф': 'f', 'х': 'h', 'ц': 'c', 'ч': 'ch', 'ш': 'sh', 
        'щ': 'shch', 'ы': 'y', 'э': 'e', 'ю': 'u', 'я': 'ya',
    'ъ': 'ie', 'ь': '', 'й': 'i'
    }, n_str = [];
        
    for ( var i = 0; i < str.length; ++i ) {
       n_str.push(
              ru[ str[i] ]
           || ru[ str[i].toLowerCase() ] == undefined && str[i]
           || ru[ str[i].toLowerCase() ].replace(/^(.)/, function ( match ) { return match.toUpperCase() })
       );
    }
    
    return n_str.join('');
}

// селектор файла с рецептами
const recipesSelector = document.getElementById("recipe-selector");

recipesSelector.addEventListener('change', (event) => {
    
    const fileList = event.target.files;
    const file = fileList[0];

    const reader = new FileReader();
    reader.readAsText(file);
    
    
    // то что происходит после загрузки файла с рецептами
    reader.onload = function() {
        let text = reader.result;
        const recipes = JSON.parse(text)["recipes"]; // все рецепты из полученного файла
        
        const button = document.querySelector("#submit");
        const answer = document.querySelector("#answer");

        // кнопка обработки. Не работает, пока не загружен файл
        button.addEventListener("click", () => {
            
            // список всех выбранных ингредиентов
            const selected = [...document.querySelectorAll("input[id]:checked")].map(
                (input) => input.id
            );
            answer.innerHTML = ""; // очистка ответа
            let lines = 0; 
            
            //сравнение массива выбранных ингредиентов с массивом всех ингредиентов
            let intersectionsList = []; 
            let intersections; 

            for (recipe of recipes) {

                intersections = recipe.ingredients.filter((item) => 
                selected.includes(rus_to_latin(item).toLowerCase())) 
                recipeIntersections = {"name": recipe.name, "intersections": intersections} // словарь {имя, пересечения}
                intersectionsList.push(recipeIntersections); // добавляем словарь в список

            }
            
            // сортировка
            intersectionsList.sort((a, b) => {
                return b.intersections.length-a.intersections.length;
            });

            // вывод на экран ингредиентов 
            
            for (i of intersectionsList) {

                if (i.intersections.length !== 0){
                let line = document.createElement("hr");
                let nextLine = document.createElement("br");
                answer.append(i.intersections.join(", ") + ": " + i.name);
                answer.append(nextLine);
                answer.append(line);
                lines++;

                }

            }   

            if (lines === 0){
                answer.innerHTML = "Таких рецептов нет!";
            }
        });
    }
});

// селектор ингредиентов
const ingredientsSelector = document.getElementById('ingredient-selector');
ingredientsSelector.addEventListener('change', (event) => {

    const fileList = event.target.files;
    const file = fileList[0];

    const reader = new FileReader() 
    reader.readAsText(file);

    
    // функционал после загрузки файла с ингредиентами 
    reader.onload = function() {
        let text = reader.result
        let ingredients = JSON.parse(text)["ingredients"]

        let inputContainer = document.getElementById("input-container")
        inputContainer.innerHTML = "";

        // вывод всех ингредиентов из файла

        for(let i = 0; i<ingredients.length; i++) {

            let ingredientCheckbox = document.createElement("input")
            ingredientCheckbox.id = rus_to_latin(ingredients[i]).toLowerCase();
            ingredientCheckbox.type = "checkbox"
            
            let ingredientLabel = document.createElement("label")
            ingredientLabel.for = ingredientCheckbox.id
            ingredientLabel.id = ingredientCheckbox.id + "-label"
            ingredientLabel.innerHTML = ingredients[i] + "\n"
            
            let nextLine = document.createElement("br")
            inputContainer.append(ingredientCheckbox);
            inputContainer.append(ingredientLabel);
            inputContainer.append(nextLine)

        }
    }
});

// кнопка очистки выбора
let clearButton = document.getElementById("clear")
clearButton.addEventListener("click", () => {

    const selected = [...document.querySelectorAll("input[id]:checked")].map(
        (input) => input.id
    );

    for (ingredient of selected) {

        const getInput = document.getElementById(ingredient)
        getInput.checked = false;

    }

});
// кнопка "Выбрать все"
let checkAllButton = document.getElementById("check-all")
checkAllButton.addEventListener("click", () => {

    const inputs = [...document.querySelectorAll("input[id]")].map(
        (input) => input.id
    );

    for (ingredient of inputs) {

        const getInput = document.getElementById(ingredient)
        getInput.checked = true;

    }

});
recipes.json
Код:
{
    "recipes": [
    {
        "name": "Пицца",
        "ingredients": [
            "Мука", "Вода", "Соль", "Колбаса", "Помидоры", "Соус"
        ]
    },
    {
        "name": "Хлеб",
        "ingredients": ["Мука", "Вода", "Соль"]
    },
    {
        "name": "Кекс",
        "ingredients": ["Мука", "Вода", "Яйца", "Соль", "Сахар"]
    }
]}
ingredients.json
Код:
{
    "ingredients": [
        "Мука",
        "Вода",
        "Сахар",
        "Яйца",
        "Соль",
        "Колбаса", 
        "Помидоры",
        "Соус"
    ]}
Другой человек подсказал такой фрагмент кода, только не знаю, как его интегрировать.
https://developer.mozilla.org/ru/doc...PI/Using_Fetch
Код:
fetch('/recipes.json')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  });
Изображения
Тип файла: png Экспертная система.png (11.6 Кб, 57 просмотров)

Последний раз редактировалось gimes; 15.06.2023 в 19:23.
gimes вне форума Ответить с цитированием
Старый 21.06.2023, 15:53   #2
uberchel
Участник клуба
 
Аватар для uberchel
 
Регистрация: 19.01.2009
Сообщений: 1,453
По умолчанию

Добрый день! если еще актуально, пишите.
uberchel вне форума Ответить с цитированием
Старый 23.06.2023, 14:32   #3
gimes
Пользователь
 
Регистрация: 17.01.2022
Сообщений: 58
По умолчанию

Задание выполнено
gimes вне форума Ответить с цитированием
Старый 23.06.2023, 15:00   #4
gimes
Пользователь
 
Регистрация: 17.01.2022
Сообщений: 58
По умолчанию

Сейчас думаю, можно ли сделать, чтобы в браузере на Андроид отображались чекбоксы и надписи для них, а также нажимались кнопки.
gimes вне форума Ответить с цитированием
Старый 25.06.2023, 18:49   #5
gimes
Пользователь
 
Регистрация: 17.01.2022
Сообщений: 58
По умолчанию

Задача решена, скрипт снова переделан.
gimes вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц



Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Разработка экспертной системы Алексей_2012 Общие вопросы по программированию, компьютерный форум 6 24.06.2023 22:27
Создание экспертной системы на Guru Тамарочка_Ст Помощь студентам 0 06.04.2013 13:21
создание экспертной системы в делфи kusainov Общие вопросы Delphi 2 29.05.2012 11:21
Создание экспертной системы Yo_Asakyra Помощь студентам 1 18.12.2011 18:25