Помогите с Python!
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
setups = {
'title': 'mnet',
'version': None,
'author': None,
}
elements = {}
def read(file):
global text, setups, elements
text = ""
lines = file.splitlines()
for line in lines:
if line.startswith('setup '):
parts = line.split('=')
if len(parts) == 2:
key = parts[0].split()[1]
value = parts[1].strip()
if key in setups:
setups[key] = value
else:
text += f"Ошибка: Ключ '{key}' не существует в setups\n"
elif line.startswith('element '):
parts = line.split('=')
if len(parts) == 2:
key = parts[0].split()[1]
value = parts[1].strip()
if value.lower().startswith('text'):
if '(' in value and ')' in value:
text_and_attributes = value.split('(')
text_value = text_and_attributes[0].strip()
attributes = text_and_attributes[1].replace(')', '').split(',')
attributes_dict = {}
for attribute in attributes:
key_val = attribute.split('=')
attributes_dict[key_val[0].strip()] = key_val[1].strip()
elements[key] = {'text': text_value, 'attributes': attributes_dict}
else:
text += f"Ошибка: Не указано значение для текста элемента '{key}'\n"
else:
elements[key] = value
return text, setups, elements
file = """
setup title = new_title
setup version = 1.0
setup author = John Doe
element element1 = Value1
element element2 = Text
element element3 = Text(text=Example text)
"""
read(file)
print(setups)
print(elements)
3 элемент не добавляется в список елементов. Даже не пробуйте использовать chatGPT в ответах
По дате
По рейтингу
В этом коде моем все то что просит сам автор вопроса
чтобы 3 элемент добавлялся в список элементов.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
setups = {
'title': 'mnet',
'version': None,
'author': None,
}
elements = {}
def read(file):
global setups, elements
text = ""
for line in file.splitlines():
parts = line.split('=', 1)
if len(parts) == 2:
key, value = parts[0].split()[1], parts[1].strip()
if line.startswith('setup '):
setups[key] = value if key in setups else f"Ошибка: Ключ '{
key}' не существует в setups"
elif line.startswith('element '):
if value.lower().startswith('text'):
if '(' in value and ')' in value:
text_value, attributes_str = value.split('(', 1)
# Remove trailing ')'
attributes_str = attributes_str[:-1]
attributes = [pair.split('=')
for pair in attributes_str.split(',')]
elements[key] = {
'text': text_value.strip(),
'attributes': {k.strip(): v.strip() for k, v in attributes}
}
else:
text += f"Ошибка: Не указано значение для текста элемента '{
key}'\n"
else:
elements[key] = value
return text, setups, elements
# Пример использования
file = """
setup title = new_title
setup version = 1.0
setup author = John Doe
element element1 = Value1
element element2 = Text(text=Example text)
element element3 = Text(text=Example text)
"""
result = read(file)
print(result)
Попробуй так:
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
setups = {
'title': 'mnet',
'version': None,
'author': None,
}
elements = {}
def read(file):
global text, setups, elements
text = ""
lines = file.splitlines()
for line in lines:
if line.startswith('setup '):
parts = line.split('=')
if len(parts) == 2:
key = parts[0].split()[1]
value = parts[1].strip()
if key in setups:
setups[key] = value
else:
text += f"Ошибка: Ключ '{key}' не существует в setups\n"
elif line.startswith('element '):
parts = line.split('=')
if len(parts) == 2:
key = parts[0].split()[1]
value = parts[1].strip()
# Проверяем на "Text", а не на "text"
if value.startswith('Text'):
if '(' in value and ')' in value:
text_and_attributes = value.split('(')
text_value = text_and_attributes[0].strip()
attributes = text_and_attributes[1].replace(')', '').split(',')
attributes_dict = {}
for attribute in attributes:
key_val = attribute.split('=')
attributes_dict[key_val[0].strip()] = key_val[1].strip()
elements[key] = {'text': text_value, 'attributes': attributes_dict}
else:
text += f"Ошибка: Не указано значение для текста элемента '{key}'\n"
else:
elements[key] = value
return text, setups, elements
file = """
setup title = new_title
setup version = 1.0
setup author = John Doe
element element1 = Value1
element element2 = Text
element element3 = Text(text=Example text)
"""
read(file)
print(setups)
print(elements)
Он не нашел скобки в условии и ушел в ошибку на строке "файла":
1
element element2 = Text
Т.е. он проверяет есть ли скобки в строке выше:
1
if '(' in value and ')' in value:
Он их не находит, и уходит в ошибку:
1
text += f"Ошибка: Не указано значение для текста элемента '{key}'\n"
И еще, данный код:
1
parts = line.split('=')
поделит строку ниже НА 3 ЧАСТИ, т.к. там два знака "="
1
element element3 = Text(text=Example text)
Поэтому оно не пройдет условие:
1
if len(parts) == 2:
Больше по теме