最終更新 10 months ago

此程式使用 Streamlit 讓使用者讀取、編輯並儲存 YAML 文件,透過 pandas 轉換為表格格式,適用於設定檔管理與資料編輯工具。

修正履歴 4e0c209c91ff4630396f105c9b498ec695d99b69

yaml_data_editor.py Raw
1from io import StringIO
2
3import pandas as pd
4import streamlit as st
5import yaml
6
7
8# 定義 YamlHandler 類
9class YamlHandler:
10 def __init__(self, file_path):
11 self.file_path = file_path
12
13 def read_yaml(self):
14 """讀取 YAML 檔案並返回字典"""
15 with open(self.file_path, "r", encoding="utf-8") as file:
16 data = yaml.safe_load(file)
17 return data
18
19 def write_yaml(self, data):
20 """將字典寫入 YAML 檔案"""
21 with open(self.file_path, "w", encoding="utf-8") as file:
22 yaml.safe_dump(data, file, default_flow_style=False, allow_unicode=True)
23
24 def read_yaml_string(self, yaml_string):
25 """從字串讀取 YAML 資料並返回字典"""
26 file = StringIO(yaml_string)
27 data = yaml.safe_load(file)
28 return data
29
30 def write_yaml_string(self, data):
31 """將字典轉換為 YAML 格式的字串"""
32 file = StringIO()
33 yaml.safe_dump(data, file, default_flow_style=False, allow_unicode=True)
34 return file.getvalue()
35
36
37# 建立 YamlHandler 實例
38file_path = "data.yml"
39yaml_handler = YamlHandler(file_path)
40
41# 讀取 YAML 文件
42data = yaml_handler.read_yaml()
43
44# 將 YAML 資料轉換為 DataFrame
45data_df = pd.DataFrame([data])
46
47# 使用 st.data_editor 編輯資料
48edited_data_df = st.data_editor(data_df)
49
50# 如果資料有變更,更新 YAML 文件
51if st.button("Save"):
52 edited_data = edited_data_df.iloc[0].to_dict()
53 yaml_string = yaml_handler.write_yaml_string(edited_data)
54
55 # 這裡展示如何使用 StringIO 處理 YAML 字串
56 st.text_area("YAML String", yaml_string)
57
58 # 寫回 YAML 文件
59 yaml_handler.write_yaml(edited_data)
60 st.success("Data saved successfully!")
61
62# 顯示編輯後的資料
63st.write("Edited Data:", edited_data_df)
64