Следующий код YAML представляет собой очень маленькую версию анкеты, в которой содержится почти 70+ вопросов. Я хочу создать класс, который может читать yaml и сделать его динамически масштабируемым и читаемым.
Класс также должен обрабатывать ввод данных и предоставлять достаточную информацию всем, кто его читает.
Как я могу это сделать?
- question: "What is your name?"
type: text
required: true
- question: "How old are you?"
type: number
required: true
min_value: 18
max_value: 100
- question: "What is your gender?"
type: multiple_choice
choices:
- Male
- Female
- Other
required: true
- question: "Do you have any dietary restrictions?"
type: checkboxes
choices:
- Vegetarian
- Vegan
- Gluten-free
- Dairy-free
- None
- question: "Which programming languages do you know?"
type: checkboxes
choices:
- Python
- JavaScript
- Java
- C++
- Ruby
- question: "How satisfied are you with our product?"
type: scale
min_value: 1
max_value: 5
- question: "Any additional comments or feedback?"
type: textarea
Я подумывал сделать что-то подобное – правильный ли это путь?
from enum import Enum
import yaml
class QuestionKind(Enum):
TEXT = "text"
NUMBER = "number"
MULTIPLE_CHOICE = "multiple_choice"
CHECKBOXES = "checkboxes"
SCALE = "scale"
TEXTAREA = "textarea"
class Question:
def __init__(self, prompt, kind, choices=None):
self.prompt = prompt
self.kind = kind
self.choices = choices
class Quiz:
def __init__(self, questions_file):
self.questions = self.load_questions(questions_file)
self.current_index = 0
def load_questions(self, questions_file):
with open(questions_file, "r") as file:
data = yaml.safe_load(file)
questions = []
for item in data:
prompt = item["question"]
kind = QuestionKind(item["type"])
choices = item.get("choices")
question = Question(prompt, kind, choices)
questions.append(question)
return questions
def current_question(self):
if self.current_index < len(self.questions):
return self.questions[self.current_index]
else:
return None
def provide_answer(self, answer):
self.current_index += 1
# Process the answer as needed
return self.current_question()
# Usage example
quiz = Quiz("questions.yaml")
current_question = quiz.current_question()
while current_question is not None:
print("Question:", current_question.prompt)
answer = input("Your answer: ")
current_question = quiz.provide_answer(answer)
Или это лучший подход?
import sys
from pathlib import Path
import ruamel.yaml
file_in = Path('questions.yaml')
print(file_in.read_text(), end='===============\n')
class BaseQuestion:
def __init__(self, question, required=False, conditions=None):
self._question = question
self._required = required
self._value = None # to store user response to question
self._conditions = conditions or []
@classmethod
def from_yaml(cls, constructor, node):
kw = ruamel.yaml.CommentedMap()
constructor.construct_mapping(node, kw)
return cls(**kw)
def check_conditions(self, responses):
for condition in self._conditions:
question_id = condition.get('id')
operator = condition.get('operator')
value = condition.get('value')
if question_id in responses and self._compare_values(responses[question_id], operator, value):
return False
return True
def _compare_values(self, value1, operator, value2):
"""Compare two values based on the given operator"""
if operator == "==":
return value1 == value2
elif operator == "!=":
return value1 != value2
elif operator == ">":
return value1 > value2
elif operator == "=":
return value1 >= value2
elif operator == "
Подробнее здесь: https://stackoverflow.com/questions/765 ... ith-python
Как создать динамическую анкету Yaml с помощью Python? ⇐ Python
Программы на Python
-
Anonymous
1762083976
Anonymous
Следующий код YAML представляет собой очень маленькую версию анкеты, в которой содержится почти 70+ вопросов. Я хочу создать класс, который может читать yaml и сделать его динамически масштабируемым и читаемым.
Класс также должен обрабатывать ввод данных и предоставлять достаточную информацию всем, кто его читает.
Как я могу это сделать?
- question: "What is your name?"
type: text
required: true
- question: "How old are you?"
type: number
required: true
min_value: 18
max_value: 100
- question: "What is your gender?"
type: multiple_choice
choices:
- Male
- Female
- Other
required: true
- question: "Do you have any dietary restrictions?"
type: checkboxes
choices:
- Vegetarian
- Vegan
- Gluten-free
- Dairy-free
- None
- question: "Which programming languages do you know?"
type: checkboxes
choices:
- Python
- JavaScript
- Java
- C++
- Ruby
- question: "How satisfied are you with our product?"
type: scale
min_value: 1
max_value: 5
- question: "Any additional comments or feedback?"
type: textarea
Я подумывал сделать что-то подобное – правильный ли это путь?
from enum import Enum
import yaml
class QuestionKind(Enum):
TEXT = "text"
NUMBER = "number"
MULTIPLE_CHOICE = "multiple_choice"
CHECKBOXES = "checkboxes"
SCALE = "scale"
TEXTAREA = "textarea"
class Question:
def __init__(self, prompt, kind, choices=None):
self.prompt = prompt
self.kind = kind
self.choices = choices
class Quiz:
def __init__(self, questions_file):
self.questions = self.load_questions(questions_file)
self.current_index = 0
def load_questions(self, questions_file):
with open(questions_file, "r") as file:
data = yaml.safe_load(file)
questions = []
for item in data:
prompt = item["question"]
kind = QuestionKind(item["type"])
choices = item.get("choices")
question = Question(prompt, kind, choices)
questions.append(question)
return questions
def current_question(self):
if self.current_index < len(self.questions):
return self.questions[self.current_index]
else:
return None
def provide_answer(self, answer):
self.current_index += 1
# Process the answer as needed
return self.current_question()
# Usage example
quiz = Quiz("questions.yaml")
current_question = quiz.current_question()
while current_question is not None:
print("Question:", current_question.prompt)
answer = input("Your answer: ")
current_question = quiz.provide_answer(answer)
Или это лучший подход?
import sys
from pathlib import Path
import ruamel.yaml
file_in = Path('questions.yaml')
print(file_in.read_text(), end='===============\n')
class BaseQuestion:
def __init__(self, question, required=False, conditions=None):
self._question = question
self._required = required
self._value = None # to store user response to question
self._conditions = conditions or []
@classmethod
def from_yaml(cls, constructor, node):
kw = ruamel.yaml.CommentedMap()
constructor.construct_mapping(node, kw)
return cls(**kw)
def check_conditions(self, responses):
for condition in self._conditions:
question_id = condition.get('id')
operator = condition.get('operator')
value = condition.get('value')
if question_id in responses and self._compare_values(responses[question_id], operator, value):
return False
return True
def _compare_values(self, value1, operator, value2):
"""Compare two values based on the given operator"""
if operator == "==":
return value1 == value2
elif operator == "!=":
return value1 != value2
elif operator == ">":
return value1 > value2
elif operator == "=":
return value1 >= value2
elif operator == "
Подробнее здесь: [url]https://stackoverflow.com/questions/76544857/how-to-make-a-dynamic-yaml-questionnaire-with-python[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия