from io import StringIO import pandas as pd import streamlit as st import yaml # 定義 YamlHandler 類 class YamlHandler: def __init__(self, file_path): self.file_path = file_path def read_yaml(self): """讀取 YAML 檔案並返回字典""" with open(self.file_path, "r", encoding="utf-8") as file: data = yaml.safe_load(file) return data def write_yaml(self, data): """將字典寫入 YAML 檔案""" with open(self.file_path, "w", encoding="utf-8") as file: yaml.safe_dump(data, file, default_flow_style=False, allow_unicode=True) def read_yaml_string(self, yaml_string): """從字串讀取 YAML 資料並返回字典""" file = StringIO(yaml_string) data = yaml.safe_load(file) return data def write_yaml_string(self, data): """將字典轉換為 YAML 格式的字串""" file = StringIO() yaml.safe_dump(data, file, default_flow_style=False, allow_unicode=True) return file.getvalue() # 建立 YamlHandler 實例 file_path = "data.yml" yaml_handler = YamlHandler(file_path) # 讀取 YAML 文件 data = yaml_handler.read_yaml() # 將 YAML 資料轉換為 DataFrame data_df = pd.DataFrame([data]) # 使用 st.data_editor 編輯資料 edited_data_df = st.data_editor(data_df) # 如果資料有變更,更新 YAML 文件 if st.button("Save"): edited_data = edited_data_df.iloc[0].to_dict() yaml_string = yaml_handler.write_yaml_string(edited_data) # 這裡展示如何使用 StringIO 處理 YAML 字串 st.text_area("YAML String", yaml_string) # 寫回 YAML 文件 yaml_handler.write_yaml(edited_data) st.success("Data saved successfully!") # 顯示編輯後的資料 st.write("Edited Data:", edited_data_df)