最后活跃于 10 months ago

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

timmy 修订了这个 Gist 10 months ago. 转到此修订

没有任何变更

timmy 修订了这个 Gist 2 years ago. 转到此修订

1 file changed, 63 insertions

yaml_data_editor.py(文件已创建)

@@ -0,0 +1,63 @@
1 + from io import StringIO
2 +
3 + import pandas as pd
4 + import streamlit as st
5 + import yaml
6 +
7 +
8 + # 定義 YamlHandler 類
9 + class 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 實例
38 + file_path = "data.yml"
39 + yaml_handler = YamlHandler(file_path)
40 +
41 + # 讀取 YAML 文件
42 + data = yaml_handler.read_yaml()
43 +
44 + # 將 YAML 資料轉換為 DataFrame
45 + data_df = pd.DataFrame([data])
46 +
47 + # 使用 st.data_editor 編輯資料
48 + edited_data_df = st.data_editor(data_df)
49 +
50 + # 如果資料有變更,更新 YAML 文件
51 + if 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 + # 顯示編輯後的資料
63 + st.write("Edited Data:", edited_data_df)
上一页 下一页