У меня проблемы с кодом, может кто-нибудь мне помочь? Прошу прощения за слова на португальском, я не обратил на это внимPython

Программы на Python
Ответить Пред. темаСлед. тема
Anonymous
 У меня проблемы с кодом, может кто-нибудь мне помочь? Прошу прощения за слова на португальском, я не обратил на это вним

Сообщение Anonymous »

Код: Выделить всё

import os
import openpyxl
import time
from openpyxl import Workbook

# Directory and path settings for saving spreadsheets project_path = "D:\\project spreadsheets"
learning_path = os.path.join(project_path, "learning") knowledge_base_path = os.path.join(project_path, "knowledge base")
error_log_path = os.path.join(project_path, "error log") new_sheets_path = os.path.join(project_path, "new sheets")

# Function to load data from the knowledge base
def load_knowledge_base_data():
data = []
for file in os.listdir(knowledge_base_path):
if file.endswith('.xlsx'):
file_path = os.path.join(knowledge_base_path, file)
wb = openpyxl.load_workbook(file_path, data_only=True)
for sheet in wb.sheetnames:
ws = wb[sheet] # Check if the sheet is of type Chartsheet
if ws.sheet_state == 'chart':
continue # Ignore Chartsheets
try:
for row in ws.iter_rows(values_only=True):
data.append(row)
except Exception as e:
logar_erro(f"Error reading sheet {file}, sheet {sheet}: {str(e)}")
return dados

# Function to generate spreadsheets based on user command
def gerar_planilha(comando_usuario):
# Logic to process user command and generate spreadsheets
if "orçamento" in comando_ussuario.lower():
return criar_planilha_orcamento()
elif "vendas de frutas" in user_command.lower():
return create_fruit_sales_sheet()
elif "data analysis" in user_command.lower():
return create_data_analysis()
else:
log_error(f"Unrecognized or unsupported command: {user_command}")
return None

# Function to create complex data analysis spreadsheets
def create_data_analysis():
wb = Workbook()
ws = wb.active
ws.title = "Data Analysis" # Basic example of filling with fictitious data
data = [
["Date", "Sales", "Cost", "Profit"],
["2024-01", 15000, 5000, "=B2-C2"],
["2024-02", 20000, 7000, "=B3-C3"], ["2024-03", 25000, 8000, "=B4-C4"]
]
for line in data:
ws.append(line) # Saves the generated spreadsheet
path_planilha = os.path.join(novas_planilhas_path, "analise_dados.xlsx")
wb.save(path_planilha)
return path_planilha

# Function to log errors
def logar_erro(message):
with open(os.path.join(log_erros_path, "log_erros.txt"), "a") as log_file:
log_file.write(mensage + "\n")

# Function for the "learn now" function
def aprender_agora():
dados_base = carga_dados_base_conhecimento()
tempo_inicio = time.time()
while time.time() - tempo_inicio < 300: # 5 minutes
wb = Workbook()
ws = wb.active
ws.title = f"Learning {time.strftime('%Y%m%d_%H%M%S')}"
# Generates spreadsheets based on the loaded data
for index, data in enumerate(data_base):
ws.append(data) # Saves the generated spreadsheet
path_planilha = os.path.join(learning_path, f"learning_{index + 1}.xlsx")
wb.save(path_planilha)
print(f"Spreadsheet generated and saved in: {path_planilha}")

# Progress log
# Main function to run the system
def main():
if not os.path.exists(new_planilhas_path):
os.makedirs(new_planilhas_path)
if not os.path.exists(learning_path): os.makedirs(learning_path)
user_command = input("Enter a command or 'learn now': ")
if user_command.lower() == "learn now":
learn_now()
else:
generate_plan(user_command)

if __name__ == "__main__":
main()
Я создаю программу обучения машинному обучению, чтобы иметь возможность создавать любые типы электронных таблиц в Excel, включая информационные панели, с помощью прямых команд. В качестве основы у меня есть бесчисленные электронные таблицы в формате PDF, которые AI Следует использовать для изучения основных и расширенных принципов работы с электронными таблицами, но у меня не получается программировать.

Подробнее здесь: https://stackoverflow.com/questions/790 ... -the-words
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»