byzh-core 0.0.2.2__tar.gz → 0.0.2.4__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.
Files changed (40) hide show
  1. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/PKG-INFO +1 -1
  2. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/B_os.py +28 -1
  3. byzh_core-0.0.2.4/byzh_core/Btable/__init__.py +4 -0
  4. byzh_core-0.0.2.4/byzh_core/Btable/auto_table.py +398 -0
  5. {byzh_core-0.0.2.2/byzh_core/Btable → byzh_core-0.0.2.4/byzh_core/Btable/obsolete}/auto_table.py +5 -5
  6. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Btqdm/my_tqdm.py +2 -2
  7. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/__init__.py +1 -1
  8. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core.egg-info/PKG-INFO +1 -1
  9. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core.egg-info/SOURCES.txt +3 -3
  10. byzh_core-0.0.2.2/byzh_core/Btable/obsolete/__init__.py +0 -0
  11. byzh_core-0.0.2.2/byzh_core/Btable/obsolete/b_auto_table.py +0 -321
  12. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/LICENSE +0 -0
  13. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/README.md +0 -0
  14. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Barchive/__init__.py +0 -0
  15. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Barchive/archive.py +0 -0
  16. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bbasic/__init__.py +0 -0
  17. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bbasic/text_style.py +0 -0
  18. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bconfig/__init__.py +0 -0
  19. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bconfig/config.py +0 -0
  20. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bmath/__init__.py +0 -0
  21. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bmath/divides.py +0 -0
  22. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bmath/get_norm.py +0 -0
  23. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bos/B_os.py +0 -0
  24. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bos/__init__.py +0 -0
  25. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bos/make.py +0 -0
  26. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bos/remove.py +0 -0
  27. {byzh_core-0.0.2.2/byzh_core/Btable → byzh_core-0.0.2.4/byzh_core/Btable/obsolete}/__init__.py +0 -0
  28. {byzh_core-0.0.2.2/byzh_core/Btable → byzh_core-0.0.2.4/byzh_core/Btable/obsolete}/row_table.py +0 -0
  29. {byzh_core-0.0.2.2/byzh_core/Btable → byzh_core-0.0.2.4/byzh_core/Btable/obsolete}/xy_table.py +0 -0
  30. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bterminal/__init__.py +0 -0
  31. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bterminal/cmd.py +0 -0
  32. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Btqdm/__init__.py +0 -0
  33. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bwriter/__init__.py +0 -0
  34. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bwriter/globalwriter.py +0 -0
  35. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core/Bwriter/writer.py +0 -0
  36. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core.egg-info/dependency_links.txt +0 -0
  37. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core.egg-info/requires.txt +0 -0
  38. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/byzh_core.egg-info/top_level.txt +0 -0
  39. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/setup.cfg +0 -0
  40. {byzh_core-0.0.2.2 → byzh_core-0.0.2.4}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: byzh_core
3
- Version: 0.0.2.2
3
+ Version: 0.0.2.4
4
4
  Summary: byzh_core是byzh系列的核心库,包含了一些常用的工具函数和类。
5
5
  Author: byzh_rc
6
6
  License: MIT
@@ -56,4 +56,31 @@ def rm(path):
56
56
  if os.path.isdir(path):
57
57
  shutil.rmtree(path)
58
58
  if os.path.isfile(path):
59
- os.remove(path)
59
+ os.remove(path)
60
+
61
+ def get_dirpaths_in_dir(root_dir_path, unwanted_dirname=['__pycache__']):
62
+ result = []
63
+ for root, dirs, files in os.walk(root_dir_path):
64
+ path = Path(root)
65
+ if path.name in unwanted_dirname:
66
+ continue
67
+ result.append(path)
68
+
69
+ result = result[1:]
70
+
71
+ return result
72
+
73
+ def get_filepaths_in_dir(root_dir_path, unwanted_name=[], unwanted_suffix=['.pyc']):
74
+ file_paths = []
75
+ for root, dirs, files in os.walk(root_dir_path):
76
+ for file in files:
77
+ file_path = os.path.join(root, file)
78
+ file_path = Path(file_path)
79
+ if file_path.name in unwanted_name or file_path.suffix in unwanted_suffix:
80
+ continue
81
+ file_paths.append(file_path)
82
+ return file_paths
83
+
84
+ if __name__ == '__main__':
85
+ print(get_dirpaths_in_dir(r'E:\byzh_workingplace\byzh-rc-to-pypi\uploadToPypi_core\byzh_core'))
86
+ print(get_filepaths_in_dir(r'E:\byzh_workingplace\byzh-rc-to-pypi\uploadToPypi_core\byzh_core'))
@@ -0,0 +1,4 @@
1
+ from .auto_table import B_Table2d
2
+
3
+
4
+ __all__ = ['B_Table2d']
@@ -0,0 +1,398 @@
1
+ import copy
2
+ import math
3
+ import os
4
+ from pathlib import Path
5
+ from typing import List, Tuple, Union
6
+ Seq = Union[List, Tuple]
7
+ try:
8
+ from wcwidth import wcswidth
9
+ except ImportError:
10
+ raise ImportError("[table] 请先安装wcwidth库: pip install wcwidth")
11
+
12
+ def get_width(string):
13
+ return wcswidth(string)
14
+
15
+ def get_maxwidth_2d(matrix):
16
+ widths = [0 for _ in range(len(matrix[0]))]
17
+ for row in matrix:
18
+ for i, element in enumerate(row):
19
+ if element is None:
20
+ element = ' '
21
+ widths[i] = max(widths[i], get_width(element))
22
+
23
+ diff_matrix = [[0 for _ in range(len(matrix[0]))] for _ in range(len(matrix))]
24
+ for i in range(len(matrix)):
25
+ for j in range(len(matrix[0])):
26
+ element = matrix[i][j]
27
+ if element is None:
28
+ element = ' '
29
+ diff_matrix[i][j] = widths[j] - get_width(element)
30
+
31
+ return widths, diff_matrix
32
+
33
+ def get_T_matrix(matrix):
34
+ new_matrix = [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
35
+ return new_matrix
36
+
37
+ def strs2matrix(str_lst):
38
+ str_lst = [x.strip() for x in str_lst if len(x.strip()) > 0]
39
+ str_lst.pop(-1)
40
+ str_lst.pop(2)
41
+ dividing_line = str_lst.pop(0)
42
+ indexes = [i for i, c in enumerate(dividing_line) if c == '+']
43
+ row_cnt = len(str_lst)
44
+ col_cnt = len(indexes) - 1
45
+
46
+
47
+ matrix = []
48
+ for i in range(row_cnt):
49
+ row = []
50
+ for j in range(col_cnt):
51
+ start = indexes[j] + 1
52
+ end = indexes[j+1]
53
+ row.append(str_lst[i][start:end].strip())
54
+ matrix.append(row)
55
+
56
+ row_name, col_name = matrix[0][0].split(' \\ ')
57
+
58
+ return matrix, row_name, col_name
59
+
60
+
61
+ class Matrix2d:
62
+ def __init__(self, row_name='x', col_name='y'):
63
+ self.row_name = row_name
64
+ self.col_name = col_name
65
+ self.matrix = [[row_name + ' | ' + col_name]]
66
+
67
+ def get_rows(self): # 包含left_upper
68
+ if self.matrix == [[]]:
69
+ return []
70
+ return [x[0] for x in self.matrix]
71
+ def get_cols(self): # 包含left_upper
72
+ return self.matrix[0]
73
+ def set_by_str(self, row, col, value):
74
+ row, col, value = str(row), str(col), str(value)
75
+
76
+ rows = self.get_rows()
77
+ cols = self.get_cols()
78
+
79
+ if row in rows:
80
+ row_index = rows.index(row)
81
+ else:
82
+ row_index = len(rows)
83
+ if col in cols:
84
+ col_index = cols.index(col)
85
+ else:
86
+ col_index = len(cols)
87
+
88
+ self.set_by_index(row_index, col_index, row, col, value)
89
+
90
+ def set_by_index(self, row_index, col_index, row, col, value):
91
+ row, col, value = str(row), str(col), str(value)
92
+
93
+ rows = self.get_rows()
94
+ cols = self.get_cols()
95
+
96
+ if row_index < len(rows):
97
+ pass
98
+ elif row_index == len(rows):
99
+ self.matrix.append([row] + [None] * (len(cols) - 1))
100
+
101
+ if col_index < len(cols):
102
+ pass
103
+ elif col_index == len(cols):
104
+ self.matrix[0].append(col)
105
+ for i in range(1, len(self.matrix)):
106
+ self.matrix[i].append(None)
107
+
108
+ self.matrix[row_index][col_index] = value
109
+
110
+ def get_by_str(self, row, col):
111
+ row, col = str(row), str(col)
112
+
113
+ rows = self.get_rows()
114
+ cols = self.get_cols()
115
+ if row in rows and col in cols:
116
+ row_index = rows.index(row)
117
+ col_index = cols.index(col)
118
+ return self.get_by_index(row_index, col_index)
119
+ else:
120
+ raise ValueError(f"row {row} or col {col} not found in table")
121
+
122
+ def get_by_index(self, row_index, col_index):
123
+ rows = self.get_rows()
124
+ cols = self.get_cols()
125
+ if row_index < len(rows) and col_index < len(cols):
126
+ return self.matrix[row_index][col_index]
127
+ else:
128
+ raise ValueError(f"row_index {row_index} or col_index {col_index} out of range")
129
+
130
+ def T(self):
131
+ new_matrix = get_T_matrix(self.matrix)
132
+ new_left_upper = self.col_name + ' \\ ' + self.row_name
133
+ new_matrix[0][0] = new_left_upper
134
+
135
+ self.row_name, self.col_name = self.col_name, self.row_name
136
+
137
+ self.matrix = new_matrix
138
+
139
+ return self
140
+ def __str__(self):
141
+ result = ''
142
+ for x in self.matrix:
143
+ result += str(x) + '\n'
144
+ return result
145
+
146
+
147
+ class Dict1d:
148
+ def __init__(self, dictionary=None):
149
+ self.dict = {}
150
+ if dictionary:
151
+ for key, value in dictionary.items():
152
+ self[key] = value
153
+
154
+ def __getitem__(self, key):
155
+ key = str(key)
156
+ return self.dict[key]
157
+ def __setitem__(self, key, value): # 用于最底层赋值
158
+ key, value = str(key), str(value)
159
+ self.dict[key] = value
160
+ def set(self, key, value): # 用于非底层赋值(防止把子dict变为str)
161
+ key = str(key)
162
+ self.dict[key] = value
163
+
164
+
165
+ def keys(self):
166
+ return self.dict.keys()
167
+
168
+ def values(self):
169
+ return self.dict.values()
170
+
171
+ def items(self):
172
+ return self.dict.items()
173
+
174
+ def copy(self):
175
+ return copy.deepcopy(self)
176
+
177
+ def __str__(self):
178
+ return str(self.dict)
179
+
180
+ def __repr__(self):
181
+ return str(self.dict)
182
+
183
+ class Dict2d:
184
+ def __init__(self):
185
+ self.dict = Dict1d()
186
+
187
+ # 先实现setitem,再实现getitem
188
+ def __getitem__(self, key):
189
+ key = str(key)
190
+ if key not in self.dict.keys():
191
+ self[key] = Dict1d()
192
+ return self.dict[key]
193
+ def __setitem__(self, key, new_dict: Dict1d | dict):
194
+ key = str(key)
195
+ self.dict.set(key, Dict1d(new_dict))
196
+ def __str__(self):
197
+ return str(self.dict)
198
+
199
+ class B_Table2d:
200
+ def __init__(self, row_name='x', col_name='y', auto_adaptive=False, narrow_better=True):
201
+ '''
202
+
203
+ :param row_name:
204
+ :param col_name:
205
+ :param auto_adaptive: 是否采取自动翻转的策略,来提升显示效果
206
+ :param narrow_better: 在auto_adaptive=True的情况下,是否优先选择横向窄的表格,避免换行显示
207
+ '''
208
+ self.row_name = row_name
209
+ self.col_name = col_name
210
+ self.auto_adaptive = auto_adaptive
211
+ self.narrow_better = narrow_better
212
+
213
+ self.matrix2d = Matrix2d(row_name, col_name) # 用于输出
214
+ self.dict2d = Dict2d() # 用于输入
215
+
216
+ # 判断是否改变
217
+ self.is_changed = False
218
+
219
+ def __getitem__(self, row):
220
+ self.is_changed = True
221
+
222
+ row = str(row)
223
+ return self.dict2d[row]
224
+
225
+ def __setitem__(self, row, new_dict):
226
+ self.is_changed = True
227
+
228
+ row = str(row)
229
+ self.dict2d[row] = new_dict
230
+
231
+ def from_txt(self, txt_path, use_txt_name:bool=False):
232
+ '''
233
+
234
+ :param txt_path:
235
+ :param use_txt_name: 默认使用init时的row_name和col_name
236
+ :return:
237
+ '''
238
+ with open(txt_path, 'r', encoding='utf-8') as f:
239
+ lines = f.readlines()
240
+ matrix, row_name, col_name = strs2matrix(lines)
241
+ if {self.row_name, self.col_name} != {row_name, col_name}:
242
+ raise ValueError(f"行头列头正反均不对应,请检查: [{self.row_name}, {self.col_name}] ❌ [{row_name}, {col_name}]")
243
+
244
+ if use_txt_name:
245
+ self.row_name = row_name
246
+ self.col_name = col_name
247
+ self.matrix2d = Matrix2d(self.row_name, self.col_name)
248
+ self.matrix2d.matrix = matrix
249
+ else:
250
+ left_upper = self.row_name + ' \\ ' + self.col_name
251
+ matrix[0][0] = left_upper
252
+ if self.row_name == row_name and self.col_name == col_name:
253
+ self.matrix2d = Matrix2d(self.row_name, self.col_name)
254
+ self.matrix2d.matrix = matrix
255
+ elif self.row_name == col_name and self.col_name == row_name:
256
+ self.matrix2d = Matrix2d(self.col_name, self.row_name)
257
+ self.matrix2d.matrix = get_T_matrix(matrix)
258
+
259
+ self.__matrix2dict()
260
+
261
+ def to_txt(self, txt_path):
262
+ with open(txt_path, 'w', encoding='utf-8') as f:
263
+ f.write(str(self))
264
+
265
+ def to_strs(self):
266
+ if self.is_changed:
267
+ self.__dict2matrix()
268
+ if self.__if_need_T():
269
+ self.T()
270
+
271
+ result = []
272
+
273
+ # 计算宽度
274
+ widths, diff_matrix = get_maxwidth_2d(self.matrix2d.matrix)
275
+
276
+ for i in range(len(self.matrix2d.matrix)):
277
+ elements = []
278
+ for j in range(len(self.matrix2d.matrix[i])):
279
+ element = self.matrix2d.matrix[i][j]
280
+ if element is None:
281
+ element = ' '
282
+ diff = diff_matrix[i][j]
283
+ diff_left = diff // 2
284
+ diff_right = diff - diff_left
285
+ element = ' '*diff_left + str(element) + ' '*diff_right
286
+ elements.append(element)
287
+ row = ' | '.join(elements)
288
+ row = '| ' + row + ' |'
289
+ result.append(row)
290
+
291
+ # 添加三行分隔线
292
+ dividing_line = '+' + '+'.join(['-' * (widths[i] + 2) for i in range(len(widths))]) + '+'
293
+ result.append(dividing_line)
294
+ result.insert(1, dividing_line)
295
+ result.insert(0, dividing_line)
296
+
297
+ return result
298
+
299
+ def to_str(self):
300
+ return '\n'.join(self.to_strs())
301
+
302
+ def __str__(self):
303
+ return self.to_str()
304
+
305
+ def __repr__(self):
306
+ if self.is_changed:
307
+ self.__dict2matrix()
308
+
309
+ result = ''
310
+ for x in self.matrix2d.matrix:
311
+ result += str(x) + '\n'
312
+ return result
313
+
314
+ def T(self):
315
+ if self.is_changed:
316
+ self.__dict2matrix()
317
+ self.matrix2d.T()
318
+ self.row_name, self.col_name = self.col_name, self.row_name
319
+ self.__matrix2dict()
320
+
321
+ return self
322
+
323
+ def __matrix2dict(self): # __
324
+ keys1 = self.matrix2d.get_rows()[1:]
325
+ keys2 = self.matrix2d.get_cols()[1:]
326
+ self.dict2d = Dict2d()
327
+ for i, key1 in enumerate(keys1):
328
+ for j, key2 in enumerate(keys2):
329
+ value = self.matrix2d.get_by_index(i+1, j+1)
330
+ self.dict2d[key1][key2] = value
331
+
332
+ self.is_changed = False
333
+
334
+ def __dict2matrix(self): # __
335
+ left_upper = self.row_name + ' \\ ' + self.col_name
336
+ # 处理keys1和keys2
337
+ keys1 = [left_upper] + list(self.dict2d.dict.keys())
338
+ keys2 = [left_upper]
339
+
340
+ temp = []
341
+ for key1 in self.dict2d.dict.keys():
342
+ for key2 in self.dict2d.dict[key1].keys():
343
+ if key2 not in temp:
344
+ temp.append(key2)
345
+
346
+ keys2.extend(temp)
347
+
348
+ # 处理matrix框架
349
+ matrix = [keys2]
350
+ for x in keys1[1:]:
351
+ matrix.append([x] + [None] * (len(keys2) - 1))
352
+
353
+ # 构建matrix2d
354
+ self.matrix2d = Matrix2d(self.row_name, self.col_name)
355
+ self.matrix2d.matrix = matrix
356
+ for row in self.dict2d.dict.keys():
357
+ for col in self.dict2d.dict[row].keys():
358
+ value = self.dict2d.dict[row][col]
359
+ self.matrix2d.set_by_str(row, col, value)
360
+
361
+ self.is_changed = False
362
+ def __if_need_T(self):
363
+ '''
364
+ 尽管T,但只是出来的str是T过的,并没有改变原来的矩阵,
365
+ 所以赋值还是原来的字符索引
366
+ :return:
367
+ '''
368
+ if not self.auto_adaptive:
369
+ return False
370
+
371
+ now_matrix2d = self.matrix2d
372
+ T_matrix2d = copy.deepcopy(now_matrix2d).T()
373
+
374
+ now_widths, _ = get_maxwidth_2d(now_matrix2d.matrix)
375
+ T_widths, _ = get_maxwidth_2d(T_matrix2d.matrix)
376
+
377
+ now_width = sum(now_widths)
378
+ T_width = sum(T_widths)
379
+
380
+ if T_width < now_width and self.narrow_better:
381
+ return True
382
+ elif T_width > now_width and not self.narrow_better:
383
+ return True
384
+ else:
385
+ return False
386
+
387
+
388
+ if __name__ == '__main__':
389
+ a = B_Table2d(row_name='data', col_name='score', auto_adaptive=False)
390
+ # a[0][1] = 'a3'
391
+ # a[11][22] = '123'
392
+ # a[11][1] = 'dawd'
393
+ a.from_txt('./a.txt')
394
+ print(a)
395
+ # a.T()
396
+ # print(a)
397
+
398
+
@@ -172,7 +172,7 @@ class B_AutoTable:
172
172
  dir = Path(path).resolve().parent
173
173
  os.makedirs(dir, exist_ok=True)
174
174
  with open(path, 'w') as f:
175
- f.write(self.get_table_by_str())
175
+ f.write(self.to_str())
176
176
 
177
177
  def update_txt(self, path):
178
178
  '''
@@ -194,7 +194,7 @@ class B_AutoTable:
194
194
 
195
195
 
196
196
 
197
- def get_table_by_strs(self) -> List[str]:
197
+ def to_strs(self) -> List[str]:
198
198
  transpose = self._need_transpose()
199
199
  self._update_all(transpose)
200
200
  self._update_widths()
@@ -222,9 +222,9 @@ class B_AutoTable:
222
222
 
223
223
  return results
224
224
 
225
- def get_table_by_str(self) -> str:
225
+ def to_str(self) -> str:
226
226
  result = ""
227
- strs = self.get_table_by_strs()
227
+ strs = self.to_strs()
228
228
  for x in strs[:-1]:
229
229
  result += x + '\n'
230
230
  result += strs[-1]
@@ -391,7 +391,7 @@ class B_AutoTable:
391
391
  return True
392
392
  return False
393
393
  def __str__(self):
394
- return self.get_table_by_str()
394
+ return self.to_str()
395
395
 
396
396
  def __getitem__(self, index):
397
397
  index = str(index)
@@ -19,7 +19,7 @@ class B_Tqdm:
19
19
  :param total: 总数
20
20
  :param prefix: 前缀
21
21
  :param suffix: 后缀
22
- :param length: 进度条长度(字符)
22
+ :param length: 进度条长度(字符), 默认为20个字符长度
23
23
  :param fill: 填充字符
24
24
  """
25
25
  super().__init__()
@@ -64,7 +64,7 @@ class B_Tqdm:
64
64
  # 更新进度条
65
65
  if self.total is not None:
66
66
  filled_length = int(self.length * self.current // self.total)
67
- bar = self.fill * filled_length + '-' * (self.length - filled_length)
67
+ bar = self.fill * filled_length + '-' * (self.length - filled_length) * len(self.fill)
68
68
 
69
69
  sys.stdout.write(f'\r{color}{self.prefix} |{bar}|'
70
70
  f' {self.current}/{self.total} -> {elapsed_str}<{estimated_str} | {speed:.1f} it/s |'
@@ -2,4 +2,4 @@
2
2
  # class 以"B_"开头
3
3
  # function 以"b_"开头
4
4
 
5
- __version__ = '0.0.2.2'
5
+ __version__ = '0.0.2.4'
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: byzh_core
3
- Version: 0.0.2.2
3
+ Version: 0.0.2.4
4
4
  Summary: byzh_core是byzh系列的核心库,包含了一些常用的工具函数和类。
5
5
  Author: byzh_rc
6
6
  License: MIT
@@ -23,10 +23,10 @@ byzh_core/Bos/make.py
23
23
  byzh_core/Bos/remove.py
24
24
  byzh_core/Btable/__init__.py
25
25
  byzh_core/Btable/auto_table.py
26
- byzh_core/Btable/row_table.py
27
- byzh_core/Btable/xy_table.py
28
26
  byzh_core/Btable/obsolete/__init__.py
29
- byzh_core/Btable/obsolete/b_auto_table.py
27
+ byzh_core/Btable/obsolete/auto_table.py
28
+ byzh_core/Btable/obsolete/row_table.py
29
+ byzh_core/Btable/obsolete/xy_table.py
30
30
  byzh_core/Bterminal/__init__.py
31
31
  byzh_core/Bterminal/cmd.py
32
32
  byzh_core/Btqdm/__init__.py
File without changes
@@ -1,321 +0,0 @@
1
- import copy
2
- import math
3
- import os
4
- from pathlib import Path
5
- from typing import List, Tuple, Union
6
- Seq = Union[List, Tuple]
7
- try:
8
- from wcwidth import wcswidth
9
- except ImportError:
10
- raise ImportError("[table] 请先安装wcwidth库: pip install wcwidth")
11
-
12
- class MyDict:
13
- def __init__(self, init_dict = None):
14
- self.dict = dict()
15
- if type(init_dict) is dict:
16
- self.dict = init_dict.copy()
17
- if type(init_dict) is MyDict:
18
- self.dict = init_dict.dict.copy()
19
-
20
-
21
- def update(self, other_dict):
22
- self.dict.update(other_dict)
23
-
24
- def items(self):
25
- return self.dict.items()
26
- def keys(self):
27
- return self.dict.keys()
28
- def values(self):
29
- return self.dict.values()
30
- def copy(self):
31
- return MyDict(self.dict.copy())
32
- def __getitem__(self, item):
33
- return self.dict[str(item)]
34
-
35
- def __setitem__(self, key, value):
36
- key, value = str(key), str(value)
37
-
38
- if key not in self.dict.keys():
39
- self.dict.update({key: ''})
40
-
41
- self.dict[key] = value
42
-
43
- class BAutoTable:
44
- def __init__(self, x_name='x', y_name='y'):
45
- self.x_sidebars = []
46
- self.y_sidebars = []
47
- self.x_name = x_name
48
- self.y_name = y_name
49
- self.dict = dict()
50
- self._widths = dict()
51
-
52
- def set(self, x_sidebar, y_sidebar, content):
53
- x_sidebar, y_sidebar, content = str(x_sidebar), str(y_sidebar), str(content)
54
- self[x_sidebar][y_sidebar] = str(content)
55
-
56
- def get_str(self, x_sidebar, y_sidebar):
57
- return self[x_sidebar][y_sidebar]
58
- def get_int(self, x_sidebar, y_sidebar):
59
- return int(self[x_sidebar][y_sidebar])
60
- def get_float(self, x_sidebar, y_sidebar):
61
- return float(self[x_sidebar][y_sidebar])
62
- def get_bool(self, x_sidebar, y_sidebar):
63
- temp = self[x_sidebar][y_sidebar]
64
- if temp == "True" or temp == "1":
65
- return True
66
- else:
67
- return False
68
- def items(self):
69
- '''
70
- (key1, key2, value)
71
- '''
72
- result = [(x, y, self.dict[x][y]) for x in self.x_sidebars for y in self.y_sidebars]
73
- return result
74
- def copy_row(self, old_row:str, new_row:str):
75
- old_row, new_row = str(old_row), str(new_row)
76
- self[new_row] = self[old_row]
77
- def read_txt(self, path):
78
- with open(path, 'r') as f:
79
- lines = f.readlines()
80
- lines = [x.strip() for x in lines if x.startswith('|')]
81
-
82
- temp = []
83
- for string in lines:
84
- elements = string.split('|')[1:-1]
85
- elements = [x.strip() for x in elements]
86
- temp.append(elements)
87
-
88
- x_name, y_name = temp[0][0].split(' \\ ') if ('\\' in temp[0][0]) else ("x", "y")
89
- x_keys = [var[0] for var in temp[1:]]
90
- y_keys = temp[0][1:]
91
-
92
- self.x_sidebars = []
93
- self.y_sidebars = []
94
- self.x_name = x_name
95
- self.y_name = y_name
96
- self.dict = dict()
97
- self._widths = dict()
98
-
99
- for i, x_element in enumerate(x_keys):
100
- y_dict = MyDict()
101
- for j, y_element in enumerate(y_keys):
102
- y_dict.update({y_element: temp[i+1][j+1]})
103
- self.dict.update({x_element: y_dict})
104
- self._update_sidebars()
105
-
106
- def to_txt(self, path):
107
- '''
108
- 将表格内容写入文件
109
- :param path:
110
- :return:
111
- '''
112
- dir = Path(path).resolve().parent
113
- os.makedirs(dir, exist_ok=True)
114
- with open(path, 'w') as f:
115
- f.write(self.get_table_by_str())
116
-
117
- def update_txt(self, path):
118
- '''
119
- 更新表格内容\n
120
- 如果文件不存在,则创建文件
121
- :param path:
122
- :return:
123
- '''
124
- # 是否存在该文件
125
- if not os.path.exists(path):
126
- self.to_txt(path)
127
- else:
128
- new_dict = self.dict
129
- self.read_txt(path)
130
- origin_dict = self.dict
131
- self.dict = self._merge_2d_dicts(origin_dict, new_dict)
132
- self._update_sidebars()
133
-
134
- self.to_txt(path)
135
-
136
-
137
-
138
- def get_table_by_strs(self) -> List[str]:
139
- results = self._create_prefix()
140
-
141
- self._update_widths()
142
-
143
- str_dash = ''
144
- str_head = ''
145
- for y in self.y_sidebars:
146
- pre_space, suf_space = self._get_prefix_suffix(y, self._widths[y], ' ')
147
- pre_dash, suf_dash = self._get_prefix_suffix('-', self._widths[y], '-')
148
- str_head += ' ' + pre_space + y + suf_space + ' |'
149
- str_dash += '-' + pre_dash + '-' + suf_dash + '-+'
150
- results[0] += str_dash
151
- results[1] += str_head
152
- results[2] += str_dash
153
-
154
- offset = 3
155
- for index, y_dicts in enumerate(self.dict.values()):
156
- for key in self.y_sidebars:
157
- value = y_dicts[key] if key in y_dicts.keys() else ''
158
- pre_space, suf_space = self._get_prefix_suffix(value, self._widths[key], ' ')
159
- str_content = ' ' + pre_space + value + suf_space + ' |'
160
- results[index+offset] += str_content
161
-
162
- results[-1] += str_dash
163
-
164
- return results
165
-
166
- def get_table_by_str(self) -> str:
167
- result = ""
168
- strs = self.get_table_by_strs()
169
- for x in strs[:-1]:
170
- result += x + '\n'
171
- result += strs[-1]
172
-
173
- return result
174
- def print_table(self):
175
- print(self.get_table_by_str())
176
-
177
- def _merge_2d_dicts(self, origin_dict, new_dict):
178
- """
179
- 合并两个二维字典。
180
- 如果两个字典的相同键存在重叠的子键,则 new_dict 的值覆盖 origin_dict。
181
- """
182
- merged_dict = {key: value.copy() for key, value in origin_dict.items()} # 复制 origin_dict 避免修改原数据
183
- for key, sub_dict in new_dict.items():
184
- if key in merged_dict.keys():
185
- merged_dict[key].update(sub_dict) # 合并子字典
186
- else:
187
- merged_dict[key] = sub_dict # 直接添加新键
188
-
189
- return merged_dict
190
- def _update_sidebars(self):
191
- self.x_sidebars = list(self.dict.keys())
192
-
193
- temp = []
194
- for dict_y in self.dict.values():
195
- for key in dict_y.keys():
196
- if key not in temp:
197
- temp.append(key)
198
- self.y_sidebars = temp
199
-
200
- def _create_prefix(self):
201
- '''
202
- 得到
203
- +-------+
204
- | x \ y |
205
- +-------+
206
- | 1 |
207
- | 2 |
208
- | 3 |
209
- +-------+
210
- '''
211
- results = []
212
-
213
- title = self.x_name + " \ " + self.y_name
214
- self._update_sidebars()
215
- n = self._get_maxlength_from_list(self.x_sidebars)
216
- length = max(n, self._get_width(title))
217
-
218
- pre_dash, suf_dash = self._get_prefix_suffix("-", length, '-')
219
- str_dash = "+-" + pre_dash + "-" + suf_dash + "-+"
220
- results.append(str_dash)
221
-
222
- pre_space, suf_space = self._get_prefix_suffix(title, length, ' ')
223
- str_index = "| " + pre_space + title + suf_space + " |"
224
- results.append(str_index)
225
- results.append(str_dash)
226
-
227
- for x in self.x_sidebars:
228
- pre_space, suf_space = self._get_prefix_suffix(x, length, ' ')
229
- str_number = "| " + pre_space + x + suf_space + " |"
230
- results.append(str_number)
231
- results.append(str_dash)
232
-
233
- return results
234
-
235
- def _get_prefix_suffix(self, string, length, charactor=' '):
236
- prefix = ''
237
- suffix = ''
238
- str_len = self._get_width(string)
239
-
240
- delta = length - str_len
241
- if delta < 0:
242
- assert "string的宽度比length宽"
243
- elif delta == 0:
244
- pass
245
- else:
246
- prefix = charactor * math.floor(delta / 2)
247
- suffix = charactor * math.ceil(delta / 2)
248
-
249
- return prefix, suffix
250
-
251
- def _get_maxlength_from_list(self, lst: List[str]) -> int:
252
- temp = [self._get_width(x) for x in lst]
253
- if len(temp) == 0:
254
- return 0
255
- else:
256
- return max(temp)
257
-
258
- def _update_widths(self):
259
- temp = {key: self._get_width(key) for key in self.y_sidebars}
260
-
261
- # for dict_y in self.dict.values():
262
- # for key, value in dict_y.items():
263
- # width = self._get_width(value)
264
- # if width > temp[key]:
265
- # temp[key] = width
266
-
267
- matrix = self._get_width_matrix()
268
- for i in range(len(matrix)):
269
- for j in range(len(matrix[0])):
270
- if matrix[i][j] > temp[self.y_sidebars[j]]:
271
- temp[self.y_sidebars[j]] = matrix[i][j]
272
-
273
- self._widths = temp
274
- def _get_width_matrix(self):
275
- results = [[0 for _ in self.y_sidebars] for _ in self.x_sidebars]
276
- for x, dict_y in self.dict.items():
277
- for y, value in dict_y.items():
278
- results[self.x_sidebars.index(x)][self.y_sidebars.index(y)] = self._get_width(value)
279
- return results
280
-
281
- def __repr__(self):
282
- print(self._widths)
283
- def _get_width(self, string):
284
- return wcswidth(string)
285
-
286
- def __len__(self):
287
- return len(self.x_sidebars) * len(self.y_sidebars)
288
- def __contains__(self, item):
289
- for x in self.x_sidebars:
290
- for y in self.y_sidebars:
291
- if str(item) == self.dict[x][y]:
292
- return True
293
- return False
294
- def __str__(self):
295
- return self.get_table_by_str()
296
-
297
- def __getitem__(self, index):
298
- index = str(index)
299
-
300
- if index not in self.dict.keys():
301
- self.dict.update({index: MyDict()})
302
- self._update_sidebars()
303
- return self.dict[index]
304
-
305
- return self.dict[index]
306
- def __setitem__(self, index, value:MyDict|dict):
307
- index, value = str(index), MyDict(value)
308
- self.dict.update({index: value})
309
-
310
- if __name__ == '__main__':
311
- my_table = BAutoTable("x", "y")
312
-
313
- my_table[1][3] = 123
314
- my_table[2][2] = 123
315
- my_table["awa"]["12133"] = 123
316
- my_table.copy_row('awa', 'qwq')
317
- my_table['qwq'][12133] = 333
318
-
319
- # my_table.read_txt(r'E:\byzh_workingplace\byzh-rc-to-pypi\awa.txt')
320
- print(my_table)
321
- repr(my_table)
File without changes
File without changes
File without changes
File without changes