byzh-core 0.0.6.0__tar.gz → 0.0.8.0__tar.gz
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.
- {byzh_core-0.0.6.0 → byzh_core-0.0.8.0}/PKG-INFO +2 -2
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/B_os.py +1 -1
- byzh_core-0.0.8.0/byzh/core/Brecorder/__init__.py +4 -0
- byzh_core-0.0.8.0/byzh/core/Brecorder/record1d.py +71 -0
- byzh_core-0.0.8.0/byzh/core/Brecorder/record2d.py +86 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Bterminal/cmd.py +7 -6
- byzh_core-0.0.8.0/byzh/core/__init__.py +0 -0
- {byzh_core-0.0.6.0 → byzh_core-0.0.8.0}/byzh_core.egg-info/PKG-INFO +2 -2
- byzh_core-0.0.8.0/byzh_core.egg-info/SOURCES.txt +29 -0
- byzh_core-0.0.8.0/byzh_core.egg-info/top_level.txt +1 -0
- {byzh_core-0.0.6.0 → byzh_core-0.0.8.0}/setup.py +5 -5
- byzh_core-0.0.6.0/byzh_core/__init__.py +0 -5
- byzh_core-0.0.6.0/byzh_core/__main__.py +0 -9
- byzh_core-0.0.6.0/byzh_core/obsolete/Bconfig/__init__.py +0 -3
- byzh_core-0.0.6.0/byzh_core/obsolete/Bconfig/config.py +0 -328
- byzh_core-0.0.6.0/byzh_core/obsolete/__init__.py +0 -6
- byzh_core-0.0.6.0/byzh_core/obsolete/auto_table.py +0 -427
- byzh_core-0.0.6.0/byzh_core/obsolete/row_table.py +0 -175
- byzh_core-0.0.6.0/byzh_core/obsolete/xy_table.py +0 -211
- byzh_core-0.0.6.0/byzh_core.egg-info/SOURCES.txt +0 -33
- byzh_core-0.0.6.0/byzh_core.egg-info/top_level.txt +0 -1
- {byzh_core-0.0.6.0 → byzh_core-0.0.8.0}/LICENSE +0 -0
- {byzh_core-0.0.6.0 → byzh_core-0.0.8.0}/README.md +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Barchive/__init__.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Barchive/archive.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Btable/__init__.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Btable/auto_table.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Bterminal/__init__.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Bterminal/run_func.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Btqdm/__init__.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Btqdm/my_tqdm.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Butils/__init__.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Butils/decorator.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Butils/text_style.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Butils/timer.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Bwriter/__init__.py +0 -0
- {byzh_core-0.0.6.0/byzh_core → byzh_core-0.0.8.0/byzh/core}/Bwriter/writer.py +0 -0
- {byzh_core-0.0.6.0 → byzh_core-0.0.8.0}/byzh_core.egg-info/dependency_links.txt +0 -0
- {byzh_core-0.0.6.0 → byzh_core-0.0.8.0}/byzh_core.egg-info/entry_points.txt +0 -0
- {byzh_core-0.0.6.0 → byzh_core-0.0.8.0}/byzh_core.egg-info/requires.txt +0 -0
- {byzh_core-0.0.6.0 → byzh_core-0.0.8.0}/setup.cfg +0 -0
@@ -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(
|
File without changes
|
@@ -0,0 +1,29 @@
|
|
1
|
+
LICENSE
|
2
|
+
README.md
|
3
|
+
setup.py
|
4
|
+
byzh/core/B_os.py
|
5
|
+
byzh/core/__init__.py
|
6
|
+
byzh/core/Barchive/__init__.py
|
7
|
+
byzh/core/Barchive/archive.py
|
8
|
+
byzh/core/Brecorder/__init__.py
|
9
|
+
byzh/core/Brecorder/record1d.py
|
10
|
+
byzh/core/Brecorder/record2d.py
|
11
|
+
byzh/core/Btable/__init__.py
|
12
|
+
byzh/core/Btable/auto_table.py
|
13
|
+
byzh/core/Bterminal/__init__.py
|
14
|
+
byzh/core/Bterminal/cmd.py
|
15
|
+
byzh/core/Bterminal/run_func.py
|
16
|
+
byzh/core/Btqdm/__init__.py
|
17
|
+
byzh/core/Btqdm/my_tqdm.py
|
18
|
+
byzh/core/Butils/__init__.py
|
19
|
+
byzh/core/Butils/decorator.py
|
20
|
+
byzh/core/Butils/text_style.py
|
21
|
+
byzh/core/Butils/timer.py
|
22
|
+
byzh/core/Bwriter/__init__.py
|
23
|
+
byzh/core/Bwriter/writer.py
|
24
|
+
byzh_core.egg-info/PKG-INFO
|
25
|
+
byzh_core.egg-info/SOURCES.txt
|
26
|
+
byzh_core.egg-info/dependency_links.txt
|
27
|
+
byzh_core.egg-info/entry_points.txt
|
28
|
+
byzh_core.egg-info/requires.txt
|
29
|
+
byzh_core.egg-info/top_level.txt
|
@@ -0,0 +1 @@
|
|
1
|
+
byzh
|
@@ -1,14 +1,14 @@
|
|
1
|
-
from setuptools import setup,
|
2
|
-
import
|
1
|
+
from setuptools import setup, find_namespace_packages
|
2
|
+
import byzh
|
3
3
|
setup(
|
4
|
-
name='
|
5
|
-
version=
|
4
|
+
name='byzh-core',
|
5
|
+
version=byzh.__version__,
|
6
6
|
author="byzh_rc",
|
7
7
|
description="byzh_core是byzh系列的核心库,包含了一些常用的工具函数和类。",
|
8
8
|
long_description=open('README.md').read(),
|
9
9
|
long_description_content_type='text/markdown',
|
10
10
|
license='MIT',
|
11
|
-
packages=
|
11
|
+
packages=find_namespace_packages(include=["byzh.*"]),
|
12
12
|
install_requires=[
|
13
13
|
'wcwidth',
|
14
14
|
],
|
@@ -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)
|