byzh-core 0.0.6.0__py3-none-any.whl → 0.0.8.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. {byzh_core → byzh/core}/B_os.py +1 -1
  2. byzh/core/Brecorder/__init__.py +4 -0
  3. byzh/core/Brecorder/record1d.py +71 -0
  4. byzh/core/Brecorder/record2d.py +86 -0
  5. {byzh_core → byzh/core}/Bterminal/cmd.py +7 -6
  6. byzh/core/__init__.py +0 -0
  7. {byzh_core-0.0.6.0.dist-info → byzh_core-0.0.8.0.dist-info}/METADATA +2 -2
  8. byzh_core-0.0.8.0.dist-info/RECORD +26 -0
  9. byzh_core-0.0.8.0.dist-info/top_level.txt +1 -0
  10. byzh_core/__init__.py +0 -5
  11. byzh_core/__main__.py +0 -9
  12. byzh_core/obsolete/Bconfig/__init__.py +0 -3
  13. byzh_core/obsolete/Bconfig/config.py +0 -328
  14. byzh_core/obsolete/__init__.py +0 -6
  15. byzh_core/obsolete/auto_table.py +0 -427
  16. byzh_core/obsolete/row_table.py +0 -175
  17. byzh_core/obsolete/xy_table.py +0 -211
  18. byzh_core-0.0.6.0.dist-info/RECORD +0 -30
  19. byzh_core-0.0.6.0.dist-info/top_level.txt +0 -1
  20. {byzh_core → byzh/core}/Barchive/__init__.py +0 -0
  21. {byzh_core → byzh/core}/Barchive/archive.py +0 -0
  22. {byzh_core → byzh/core}/Btable/__init__.py +0 -0
  23. {byzh_core → byzh/core}/Btable/auto_table.py +0 -0
  24. {byzh_core → byzh/core}/Bterminal/__init__.py +0 -0
  25. {byzh_core → byzh/core}/Bterminal/run_func.py +0 -0
  26. {byzh_core → byzh/core}/Btqdm/__init__.py +0 -0
  27. {byzh_core → byzh/core}/Btqdm/my_tqdm.py +0 -0
  28. {byzh_core → byzh/core}/Butils/__init__.py +0 -0
  29. {byzh_core → byzh/core}/Butils/decorator.py +0 -0
  30. {byzh_core → byzh/core}/Butils/text_style.py +0 -0
  31. {byzh_core → byzh/core}/Butils/timer.py +0 -0
  32. {byzh_core → byzh/core}/Bwriter/__init__.py +0 -0
  33. {byzh_core → byzh/core}/Bwriter/writer.py +0 -0
  34. {byzh_core-0.0.6.0.dist-info → byzh_core-0.0.8.0.dist-info}/LICENSE +0 -0
  35. {byzh_core-0.0.6.0.dist-info → byzh_core-0.0.8.0.dist-info}/WHEEL +0 -0
  36. {byzh_core-0.0.6.0.dist-info → byzh_core-0.0.8.0.dist-info}/entry_points.txt +0 -0
@@ -153,5 +153,5 @@ def walk(
153
153
 
154
154
  if __name__ == '__main__':
155
155
  # print(get_dirpaths_in_dir(r'E:\byzh_workingplace\byzh-rc-to-pypi'))
156
- a = get_filepaths_in_dir(r'E:\byzh_workingplace\byzh-rc-to-pypi')
156
+ a = get_filepaths_in_dir(r'/')
157
157
  print(a)
@@ -0,0 +1,4 @@
1
+ from .record1d import B_Record1d
2
+ from .record2d import B_Record2d
3
+
4
+ __all__ = ['B_Record1d', 'B_Record2d']
@@ -0,0 +1,71 @@
1
+ import pandas as pd
2
+
3
+ from .. import B_os
4
+
5
+
6
+ class B_Record1d:
7
+ '''
8
+ recorder = Record_1d(csv_file, mode="w")
9
+ recorder.write(name="Alice", age=25, city="Shanghai")
10
+ recorder.write(name="Bob", age=30, city="Beijing")
11
+ recorder.write(name="Charlie", age=22, city="Shenzhen")
12
+ '''
13
+ def __init__(self, csv_path, mode="a"):
14
+ self.csv_path = csv_path
15
+
16
+ B_os.makedirs(csv_path)
17
+ self.data = pd.DataFrame()
18
+ if mode == "w":
19
+ B_os.rm(csv_path)
20
+ self.__read()
21
+ elif mode == "a":
22
+ self.__read()
23
+
24
+ def write(self, **kwargs):
25
+ '''
26
+ :param kwargs:
27
+ :return:
28
+
29
+ '''
30
+ # 给DataFrame增加一行
31
+ # key作为column, value作为内容
32
+ new_row = pd.DataFrame([kwargs])
33
+ self.data = pd.concat([self.data, new_row], ignore_index=True)
34
+ self.__save()
35
+
36
+ return self
37
+ def __read(self):
38
+ try:
39
+ self.data = pd.read_csv(self.csv_path)
40
+ except FileNotFoundError:
41
+ self.data = pd.DataFrame()
42
+ except pd.errors.EmptyDataError:
43
+ self.data = pd.DataFrame()
44
+
45
+ def __save(self, csv_path=None):
46
+ if csv_path is None:
47
+ csv_path = self.csv_path
48
+ self.data.to_csv(csv_path, index=False, encoding='utf-8-sig')
49
+
50
+ def __str__(self):
51
+ return str(self.data)
52
+
53
+ if __name__ == '__main__':
54
+ # 指定保存的CSV路径
55
+ csv_file = "test_data.csv"
56
+
57
+ # 创建记录器(写模式 w 表示覆盖)
58
+ recorder = B_Record1d(csv_file, mode="w")
59
+
60
+ # 写入几条数据
61
+ recorder.write(name="Alice", age=25, city="Shanghai")
62
+ recorder.write(name="Bob", age=30, city="Beijing")
63
+ recorder.write(name="Charlie", age=22, city="Shenzhen")
64
+
65
+ # 追加模式 a
66
+ recorder2 = B_Record1d(csv_file, mode="a")
67
+ recorder2.write(name="David", age=28, city="Guangzhou")
68
+
69
+ # 打印当前内容
70
+ print("CSV 当前内容:")
71
+ print(recorder2)
@@ -0,0 +1,86 @@
1
+ import pandas as pd
2
+ from typing import Any
3
+
4
+ from .. import B_os
5
+
6
+ class B_Record2d:
7
+ def __init__(self, csv_path, mode="a"):
8
+ self.csv_path = csv_path
9
+
10
+ B_os.makedirs(csv_path)
11
+ self.data = pd.DataFrame()
12
+ if mode == "w":
13
+ B_os.rm(csv_path)
14
+ self.__read()
15
+ elif mode == "a":
16
+ self.__read()
17
+
18
+ def write(self, row, col, value):
19
+ row, col, value = str(row), str(col), str(value)
20
+
21
+ # 如果行不存在,pandas 会自动创建
22
+ # 如果列不存在,pandas 也会自动扩展
23
+ self.data.loc[row, col] = value
24
+
25
+ # 保存
26
+ self.__save()
27
+
28
+ def get(self, row, col) -> Any:
29
+ row, col = str(row), str(col)
30
+ result = self.data.loc[row, col]
31
+ return result
32
+ def get_str(self, row, col) -> str:
33
+ row, col = str(row), str(col)
34
+ result = self.data.loc[row, col]
35
+ return str(result)
36
+
37
+ def get_int(self, row, col) -> int:
38
+ row, col = str(row), str(col)
39
+ result = self.data.loc[row, col]
40
+ return int(result)
41
+ def get_float(self, row, col) -> float:
42
+ row, col = str(row), str(col)
43
+ result = self.data.loc[row, col]
44
+ return float(result)
45
+ def get_bool(self, row, col) -> bool:
46
+ row, col = str(row), str(col)
47
+ result = self.data.loc[row, col]
48
+ if result == "True" or result == "true" or result == "1":
49
+ return True
50
+ elif result == "False" or result == "false" or result == "0":
51
+ return False
52
+ else:
53
+ raise ValueError(f"无法转换为布尔值 -> {result}")
54
+
55
+ def __read(self):
56
+ try:
57
+ self.data = pd.read_csv(self.csv_path, index_col=0)
58
+ except FileNotFoundError:
59
+ self.data = pd.DataFrame()
60
+ except pd.errors.EmptyDataError:
61
+ self.data = pd.DataFrame()
62
+
63
+ def __save(self, csv_path=None):
64
+ if csv_path is None:
65
+ csv_path = self.csv_path
66
+ self.data.to_csv(csv_path, index=True, encoding='utf-8-sig')
67
+
68
+ def __str__(self):
69
+ return str(self.data)
70
+
71
+ if __name__ == '__main__':
72
+ csv_file = "test_data.csv"
73
+
74
+ recorder = B_Record2d(csv_file, mode="w")
75
+
76
+ # 写入一些单元格
77
+ recorder.write("awa", "OvO", 10)
78
+ recorder.write("awa", "TwT", 20)
79
+ recorder.write("qwq", "OvO", 30)
80
+ recorder.write("qwq", "TwT", 40)
81
+
82
+ print("当前内容:")
83
+ print(recorder)
84
+
85
+ recorder = B_Record2d(csv_file, mode="a")
86
+ print(recorder)
@@ -92,21 +92,22 @@ def b_run_python(
92
92
  index = str_lst.index(string)
93
93
  str_lst[index] = string + f"\t[!!!Time limit!!!] [{h_t}h {m_t}m {s_t}s]"
94
94
 
95
- print(f"{B_Color.GREEN}====================={B_Color.RESET}")
96
- print(f"{B_Color.GREEN}BRunPython 结束:{B_Color.RESET}")
95
+ print(f"{B_Color.GREEN.value}====================={B_Color.RESET.value}")
96
+ print(f"{B_Color.GREEN.value}BRunPython 结束:{B_Color.RESET.value}")
97
97
  for string in str_lst:
98
98
  if 'Time limit' in string:
99
- print(f"\t{B_Color.YELLOW}" + string + f"{B_Color.RESET}")
99
+ print(f"\t{B_Color.YELLOW.value}" + string + f"{B_Color.RESET.value}")
100
100
  elif 'Error' in string:
101
- print(f"\t{B_Color.RED}" + string + f"{B_Color.RESET}")
101
+ print(f"\t{B_Color.RED.value}" + string + f"{B_Color.RESET.value}")
102
102
  else:
103
- print(f"\t{B_Color.GREEN}" + string + f"{B_Color.RESET}")
104
- print(f"{B_Color.GREEN}====================={B_Color.RESET}")
103
+ print(f"\t{B_Color.GREEN.value}" + string + f"{B_Color.RESET.value}")
104
+ print(f"{B_Color.GREEN.value}====================={B_Color.RESET.value}")
105
105
 
106
106
  run_log('结束')
107
107
 
108
108
 
109
109
 
110
+
110
111
  if __name__ == '__main__':
111
112
  b_run_cmd("echo hello", "echo world", "echo awa", show=True)
112
113
  # b_run_python(
byzh/core/__init__.py ADDED
File without changes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
- Name: byzh_core
3
- Version: 0.0.6.0
2
+ Name: byzh-core
3
+ Version: 0.0.8.0
4
4
  Summary: byzh_core是byzh系列的核心库,包含了一些常用的工具函数和类。
5
5
  Author: byzh_rc
6
6
  License: MIT
@@ -0,0 +1,26 @@
1
+ byzh/core/B_os.py,sha256=06JGOEheFQqvSLNKtbeo9x5V9qx5cZ8OEjAXKy6PTeM,4278
2
+ byzh/core/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
3
+ byzh/core/Barchive/__init__.py,sha256=wUdz646VS0Uhq9lwMkd3YQHCvQhLDqgADoDjFGMqIn0,65
4
+ byzh/core/Barchive/archive.py,sha256=S1hy3qYFEZr5RRmx_Mnq1s2IMUEw973ny1rKSL7J_a0,6721
5
+ byzh/core/Brecorder/__init__.py,sha256=rYlgYIhr_AcPuGkZRCitbi2_hZYyoERk4XIZ14CU1dk,108
6
+ byzh/core/Brecorder/record1d.py,sha256=0iPVzX5-x-iX02HMZSq0goekNp-_g2W3uS0ZaHlAEkY,2037
7
+ byzh/core/Brecorder/record2d.py,sha256=SIFDZVGEjizYBbp0QJl7ILCAPHdG3wcVmCvmJ3Kr2w8,2585
8
+ byzh/core/Btable/__init__.py,sha256=NlQBjp_mvObEUm4y6wXbGipkNM2N3uNIUidaJkTwFsw,62
9
+ byzh/core/Btable/auto_table.py,sha256=avMeRWydw9L8s3fU0-BSl8a2dCyreIUzW--csm5eR0g,14734
10
+ byzh/core/Bterminal/__init__.py,sha256=azRLD-kY8Tv2c3llHRBrEJIdVgYw6hAoLgzJeA4PvE0,142
11
+ byzh/core/Bterminal/cmd.py,sha256=qtT2ru1Bo3I9A_5hUXfve-aq0Jxi1jpHfcMgtmZqEHo,3925
12
+ byzh/core/Bterminal/run_func.py,sha256=B2CZSxdSrcBbt7w5_hnOYrUmwrjK5CPqbyyt_YkB_I0,1836
13
+ byzh/core/Btqdm/__init__.py,sha256=G8pvJYizvdTUI3Xw-yELXY7BbjTghCXJLdqUuDoRNZA,141
14
+ byzh/core/Btqdm/my_tqdm.py,sha256=MMYFwy5dUCzg8fzRWZ7vrpZ-q_DDqoLvywDk8rgSaSM,3578
15
+ byzh/core/Butils/__init__.py,sha256=_0aAm72oynvpFf-v9EAMSqhWBHbTt4Tn85jtv3Yf0z8,236
16
+ byzh/core/Butils/decorator.py,sha256=HaB8F80wsqQuS30jlI8C2d3SmEa0mBNfJEr5-pwGZj0,584
17
+ byzh/core/Butils/text_style.py,sha256=34u2-Rsur63iNQ0m7tHxpFWqnQZWybSxBx7vnhOhqDo,3346
18
+ byzh/core/Butils/timer.py,sha256=OLxbWWRauYjp1KwavACjoyrqrCciUiIG2ae7qgtZrVA,511
19
+ byzh/core/Bwriter/__init__.py,sha256=QcHzKs0305Pr78ZvZgcC_4miSYZh8jJQDt5TD0GIeEg,82
20
+ byzh/core/Bwriter/writer.py,sha256=ss9EWo-l7czBUlY7Fu0buvQgO5fRspYKtC2X6eaRa0c,3213
21
+ byzh_core-0.0.8.0.dist-info/LICENSE,sha256=-nRwf0Xga4AX5bsWBXXflpDpgX_U23X06oAMcdf0dSY,1089
22
+ byzh_core-0.0.8.0.dist-info/METADATA,sha256=R_g0yzV3USWUfVBtvA_G0eQO2uHS8jHbj1GholsRNqQ,371
23
+ byzh_core-0.0.8.0.dist-info/WHEEL,sha256=R0nc6qTxuoLk7ShA2_Y-UWkN8ZdfDBG2B6Eqpz2WXbs,91
24
+ byzh_core-0.0.8.0.dist-info/entry_points.txt,sha256=qoN3Uvulj0BcOQVDqsFqP2dBVQzG1QrUtC5wFsghSLo,51
25
+ byzh_core-0.0.8.0.dist-info/top_level.txt,sha256=tmaFVY8uApe6apOETSOgwz-4v5Mj4uxgRT8yNnDNZNA,5
26
+ byzh_core-0.0.8.0.dist-info/RECORD,,
@@ -0,0 +1 @@
1
+ byzh
byzh_core/__init__.py DELETED
@@ -1,5 +0,0 @@
1
- # package 以"B"开头
2
- # class 以"B_"开头
3
- # function 以"b_"开头
4
-
5
- __version__ = '0.0.6.0' # core的最后一位保持0, 留给其他包
byzh_core/__main__.py DELETED
@@ -1,9 +0,0 @@
1
- import argparse
2
-
3
- def b_zip():
4
- parser = argparse.ArgumentParser()
5
- parser.add_argument("dir_path")
6
- args = parser.parse_args()
7
-
8
- from .Barchive import b_archive_zip
9
- b_archive_zip(args.dir_path)
@@ -1,3 +0,0 @@
1
- from .config import B_Config
2
-
3
- __all__ = ['B_Config']
@@ -1,328 +0,0 @@
1
- from ...Butils import B_Color
2
-
3
-
4
- class B_Config:
5
- def __init__(self):
6
- super().__init__()
7
- self.group_lst = []
8
- self.dict_lst = []
9
-
10
- # set-方法
11
- def set(self, group, key, value):
12
- '''
13
- 添加元素
14
- '''
15
- if not isinstance(group, str):
16
- raise Exception(f"{B_Color.YELLOW}group({str(group)}) must be str{B_Color.RESET}")
17
- if not isinstance(key, str):
18
- raise Exception(f"{B_Color.YELLOW}key({str(key)}) must be str{B_Color.RESET}")
19
-
20
- if group not in self.group_lst:
21
- self.group_lst.append(group)
22
- self.dict_lst.append(dict())
23
-
24
- index = self._get_index(group)
25
- self.dict_lst[index][key] = value
26
-
27
- def set_copygroup(self, dst_group, src_group):
28
- '''
29
- 通过复制group来快速添加组
30
- '''
31
- if not isinstance(dst_group, str):
32
- raise Exception(f"{B_Color.YELLOW}group({str(dst_group)}) must be str{B_Color.RESET}")
33
- if not isinstance(src_group, str):
34
- raise Exception(f"{B_Color.YELLOW}group({str(src_group)}) must be str{B_Color.RESET}")
35
- if dst_group in self.group_lst:
36
- raise Exception(f"{B_Color.YELLOW}group({str(dst_group)}) already exist{B_Color.RESET}")
37
-
38
- import copy
39
- self.group_lst.append(dst_group)
40
- self.dict_lst.append(copy.deepcopy(self.dict_lst[self._get_index(src_group)]))
41
-
42
- def set_dictgroup(self, group, dict):
43
- '''
44
- 通过dict来快速添加组
45
- '''
46
- if group in self.group_lst:
47
- raise Exception(f"{B_Color.YELLOW}group({str(group)}) already exist{B_Color.RESET}")
48
- self.group_lst.append(group)
49
- # 把dict的键值对都化为字符串
50
- self.dict_lst.append({str(key): str(value) for key, value in dict.items()})
51
-
52
- # show-方法
53
- def show_all(self):
54
- '''
55
- 打印config
56
- '''
57
- print(f"group_cnt({len(self.group_lst)}) | {self.group_lst} \ndict_cnt:{len(self.dict_lst)}")
58
- print()
59
- for group, dict in zip(self.group_lst, self.dict_lst):
60
- print(f"{group}:\n\t{dict}")
61
-
62
- def show_group(self, group):
63
- '''
64
- 打印某个group
65
- '''
66
- result = self._get_group_str(group)
67
- print(group + ":\n" + result)
68
-
69
- # get-方法
70
- def get_str(self, group, key):
71
- '''
72
- 获取某个group的某个key的值
73
- '''
74
- self._check(group, key)
75
- index = self._get_index(group)
76
- return str(self.dict_lst[index][key])
77
-
78
- def get_int(self, group, key):
79
- '''
80
- 获取某个group的某个key的值
81
- '''
82
- self._check(group, key)
83
- index = self._get_index(group)
84
- return int(self.dict_lst[index][key])
85
-
86
- def get_float(self, group, key):
87
- '''
88
- 获取某个group的某个key的值
89
- '''
90
- self._check(group, key)
91
- index = self._get_index(group)
92
- return float(self.dict_lst[index][key])
93
-
94
- def get_bool(self, group, key):
95
- '''
96
- 获取某个group的某个key的值\n
97
- 只有value为["False", "0", "None"]时,返回False
98
- '''
99
- self._check(group, key)
100
-
101
- if self.get_str(group, key) in ["False", "0", "None"]:
102
- return False
103
- elif self.get_str(group, key) in ["True", "1"]:
104
- return True
105
- else:
106
- raise Exception(f"{B_Color.YELLOW}value({str(key)}) cannot change to bool{B_Color.RESET}")
107
-
108
- # save-方法
109
- def to_pickle(self, path):
110
- '''
111
- 保存为pickle文件(最稳定的方式)
112
- '''
113
- import pickle
114
- with open(path, 'wb') as f:
115
- pickle.dump([self.group_lst, self.dict_lst], f)
116
-
117
- def from_pickle(self, path):
118
- '''
119
- 从pickle文件中读取
120
- '''
121
- import pickle
122
- with open(path, 'rb') as f:
123
- [self.group_lst, self.dict_lst] = pickle.load(f)
124
-
125
- def to_json(self, path):
126
- '''
127
- 保存为json文件
128
- '''
129
- import json
130
- with open(path, 'w') as f:
131
- for group, group_dict in zip(self.group_lst, self.dict_lst):
132
- entry = {"group": group, "dict": group_dict}
133
- json.dump(entry, f)
134
- f.write("\n")
135
-
136
- def from_json(self, path):
137
- '''
138
- 从json文件中读取
139
- '''
140
- import json
141
- with open(path, 'r') as f:
142
- self.group_lst = []
143
- self.dict_lst = []
144
- for line in f:
145
- entry = json.loads(line.strip())
146
- self.group_lst.append(entry["group"])
147
- self.dict_lst.append(entry["dict"])
148
-
149
- def to_yaml(self, path):
150
- '''
151
- 保存为yaml文件
152
- '''
153
- import yaml
154
- with open(path, 'w') as f:
155
- yaml.dump([self.group_lst, self.dict_lst], f)
156
-
157
- def from_yaml(self, path):
158
- '''
159
- 从yaml文件中读取
160
- '''
161
- import yaml
162
- with open(path, 'r') as f:
163
- [self.group_lst, self.dict_lst] = yaml.load(f, Loader=yaml.FullLoader)
164
-
165
- def to_ini(self, path):
166
- '''
167
- 保存为ini文件
168
- '''
169
- with open(path, 'w') as f:
170
- for group, dict in zip(self.group_lst, self.dict_lst):
171
- f.write(f"[{group}]\n")
172
- for key, value in dict.items():
173
- f.write(f"{key} = {value}\n")
174
- f.write("\n")
175
-
176
- def from_ini(self, path):
177
- '''
178
- 从ini文件中读取
179
- '''
180
- self.group_lst = []
181
- self.dict_lst = []
182
- with open(path, 'r') as f:
183
- lines = f.readlines()
184
- dictionary = dict()
185
- for line in lines:
186
- line = line.strip()
187
- if line.startswith('[') and line.endswith(']'):
188
- # 如果字典非空不是dict()
189
- if dictionary != dict():
190
- self.dict_lst.append(dictionary.copy())
191
- dictionary.clear()
192
- group = line[1:-1]
193
- self.group_lst.append(group)
194
- elif line == '':
195
- continue
196
- else:
197
- if '=' in line:
198
- key, value = line.split('=', 1)
199
- # key和value去除前后空格
200
- key = key.strip()
201
- value = value.strip()
202
- dictionary[key] = value
203
- else:
204
- dictionary[line] = ''
205
- if dictionary != dict():
206
- self.dict_lst.append(dictionary.copy())
207
-
208
- def to_csv(self, path):
209
- '''
210
- 保存为csv文件
211
- '''
212
- import csv
213
- with open(path, 'w', newline='') as f:
214
- writer = csv.writer(f)
215
-
216
- # Write header: the first row is group names
217
- header = ['key'] + self.group_lst
218
- writer.writerow(header)
219
-
220
- # Find all unique keys across all groups
221
- all_keys = set()
222
- for group_dict in self.dict_lst:
223
- all_keys.update(group_dict.keys())
224
-
225
- # Write rows for each key
226
- for key in all_keys:
227
- row = [key]
228
- for group_dict in self.dict_lst:
229
- row.append(group_dict.get(key, '')) # Add value or empty if key is not present
230
- writer.writerow(row)
231
-
232
- def from_csv(self, path):
233
- '''
234
- 从csv文件中读取
235
- '''
236
- import csv
237
- with open(path, 'r') as f:
238
- reader = csv.reader(f)
239
-
240
- # Read header: the first row is group names
241
- header = next(reader)
242
- group_lst = header[1:] # The first column is 'key', rest are groups
243
- self.group_lst = group_lst
244
- self.dict_lst = [{} for _ in range(len(group_lst))] # Initialize dicts for each group
245
-
246
- # Read the key-value pairs
247
- for row in reader:
248
- key = row[0]
249
- for i, value in enumerate(row[1:], start=0):
250
- if value: # Only add value if it's not empty
251
- self.dict_lst[i][key] = value
252
-
253
- def to_table(self, path):
254
- from ..Btable import B_Table2d
255
- my_table = B_Table2d()
256
- for index, group in enumerate(self.group_lst):
257
- for key, value in self.dict_lst[index].items():
258
- my_table[group][key] = value
259
-
260
- my_table.to_txt(path)
261
-
262
- # 工具-方法
263
- def __str__(self):
264
- result = ""
265
- for group in self.group_lst:
266
- result += group + ":\n"
267
- result += self._get_group_str(group) + "\n"
268
- # 去掉最后一个\n
269
- result = result[:-1]
270
- return result
271
- def __getitem__(self, item):
272
- return self.dict_lst[item]
273
-
274
- def __setitem__(self, key, value):
275
- self.set_dictgroup(key, value)
276
-
277
- def _get_index(self, group):
278
- return self.group_lst.index(group)
279
-
280
- def _get_group_str(self, group):
281
- self._check(group)
282
- index = self._get_index(group)
283
- result = "\n".join([f"\t({key} -> {value})" for key, value in self.dict_lst[index].items()])
284
- return result
285
-
286
- def _check(self, group, key=None):
287
- # 检查group是否是字符串
288
- if not isinstance(group, str):
289
- raise Exception(f"{B_Color.YELLOW}group({str(group)}) must be str{B_Color.RESET}")
290
- # 检查group是否在group_list中
291
- if group not in self.group_lst:
292
- raise Exception(f"{B_Color.YELLOW}group({str(group)}) not found{B_Color.RESET}")
293
-
294
- if key is not None:
295
- # 检查key是否是字符串
296
- if not isinstance(key, str):
297
- raise Exception(f"{B_Color.YELLOW}key({str(key)}) must be str{B_Color.RESET}")
298
- # 检查key是否在dict中
299
- index = self._get_index(group)
300
- if key not in self.dict_lst[index]:
301
- raise Exception(f"{B_Color.YELLOW}key({str(key)}) not found{B_Color.RESET}")
302
-
303
-
304
- if __name__ == '__main__':
305
- a = B_Config()
306
-
307
- a.set('awa', 'a', 'None')
308
- a.set('awa', 'b', '123')
309
- a.set('awa', '345', '33333')
310
-
311
- a.set('awa', 'a532', 'No32ne')
312
- a.set('awa', 'b13', '123412')
313
- a.set('awa', '321345', '33342333')
314
-
315
- a.set_copygroup('default', 'qwq')
316
- a.set('qwq', '345', 'aaaaaa')
317
-
318
- a.to_csv('config.csv')
319
- a.from_csv('config.csv')
320
- # a.to_yaml('config.yaml')
321
- # a.from_yaml('config.yaml')
322
- # a.to_pickle('config.pkl')
323
- # a.from_pickle('config.pkl')
324
- # a.to_json('config.json')
325
- # a.from_json('config.json')
326
-
327
- print(a.get_str('awa', 'b13'))
328
- print(a)
@@ -1,6 +0,0 @@
1
- from .row_table import B_RowTable
2
- from .xy_table import B_XYTable
3
- from .auto_table import B_AutoTable
4
-
5
-
6
- __all__ = ['B_RowTable', 'B_XYTable', 'B_AutoTable']