pyxllib 0.3.197__py3-none-any.whl → 3.201.1__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 (127) hide show
  1. pyxllib/__init__.py +14 -21
  2. pyxllib/algo/__init__.py +8 -8
  3. pyxllib/algo/disjoint.py +54 -54
  4. pyxllib/algo/geo.py +537 -541
  5. pyxllib/algo/intervals.py +964 -964
  6. pyxllib/algo/matcher.py +389 -389
  7. pyxllib/algo/newbie.py +166 -166
  8. pyxllib/algo/pupil.py +629 -629
  9. pyxllib/algo/shapelylib.py +67 -67
  10. pyxllib/algo/specialist.py +241 -241
  11. pyxllib/algo/stat.py +494 -494
  12. pyxllib/algo/treelib.py +145 -149
  13. pyxllib/algo/unitlib.py +62 -66
  14. pyxllib/autogui/__init__.py +5 -5
  15. pyxllib/autogui/activewin.py +246 -246
  16. pyxllib/autogui/all.py +9 -9
  17. pyxllib/autogui/autogui.py +846 -852
  18. pyxllib/autogui/uiautolib.py +362 -362
  19. pyxllib/autogui/virtualkey.py +102 -102
  20. pyxllib/autogui/wechat.py +827 -827
  21. pyxllib/autogui/wechat_msg.py +421 -421
  22. pyxllib/autogui/wxautolib.py +84 -84
  23. pyxllib/cv/__init__.py +5 -5
  24. pyxllib/cv/expert.py +267 -267
  25. pyxllib/cv/imfile.py +159 -159
  26. pyxllib/cv/imhash.py +39 -39
  27. pyxllib/cv/pupil.py +9 -9
  28. pyxllib/cv/rgbfmt.py +1525 -1525
  29. pyxllib/cv/slidercaptcha.py +137 -137
  30. pyxllib/cv/trackbartools.py +251 -251
  31. pyxllib/cv/xlcvlib.py +1040 -1040
  32. pyxllib/cv/xlpillib.py +423 -423
  33. pyxllib/data/echarts.py +236 -240
  34. pyxllib/data/jsonlib.py +85 -89
  35. pyxllib/data/oss.py +72 -72
  36. pyxllib/data/pglib.py +1111 -1127
  37. pyxllib/data/sqlite.py +568 -568
  38. pyxllib/data/sqllib.py +297 -297
  39. pyxllib/ext/JLineViewer.py +505 -505
  40. pyxllib/ext/__init__.py +6 -6
  41. pyxllib/ext/demolib.py +251 -246
  42. pyxllib/ext/drissionlib.py +277 -277
  43. pyxllib/ext/kq5034lib.py +12 -12
  44. pyxllib/ext/qt.py +449 -449
  45. pyxllib/ext/robustprocfile.py +493 -497
  46. pyxllib/ext/seleniumlib.py +76 -76
  47. pyxllib/ext/tk.py +173 -173
  48. pyxllib/ext/unixlib.py +821 -827
  49. pyxllib/ext/utools.py +345 -351
  50. pyxllib/ext/webhook.py +124 -119
  51. pyxllib/ext/win32lib.py +40 -40
  52. pyxllib/ext/wjxlib.py +91 -88
  53. pyxllib/ext/wpsapi.py +124 -124
  54. pyxllib/ext/xlwork.py +9 -9
  55. pyxllib/ext/yuquelib.py +1110 -1105
  56. pyxllib/file/__init__.py +17 -17
  57. pyxllib/file/docxlib.py +757 -761
  58. pyxllib/file/gitlib.py +309 -309
  59. pyxllib/file/libreoffice.py +165 -165
  60. pyxllib/file/movielib.py +144 -148
  61. pyxllib/file/newbie.py +10 -10
  62. pyxllib/file/onenotelib.py +1469 -1469
  63. pyxllib/file/packlib/__init__.py +330 -330
  64. pyxllib/file/packlib/zipfile.py +2441 -2441
  65. pyxllib/file/pdflib.py +422 -426
  66. pyxllib/file/pupil.py +185 -185
  67. pyxllib/file/specialist/__init__.py +681 -685
  68. pyxllib/file/specialist/dirlib.py +799 -799
  69. pyxllib/file/specialist/download.py +193 -193
  70. pyxllib/file/specialist/filelib.py +2825 -2829
  71. pyxllib/file/xlsxlib.py +3122 -3131
  72. pyxllib/file/xlsyncfile.py +341 -341
  73. pyxllib/prog/__init__.py +5 -5
  74. pyxllib/prog/cachetools.py +58 -64
  75. pyxllib/prog/deprecatedlib.py +233 -233
  76. pyxllib/prog/filelock.py +42 -42
  77. pyxllib/prog/ipyexec.py +253 -253
  78. pyxllib/prog/multiprogs.py +940 -940
  79. pyxllib/prog/newbie.py +451 -451
  80. pyxllib/prog/pupil.py +1208 -1197
  81. pyxllib/prog/sitepackages.py +33 -33
  82. pyxllib/prog/specialist/__init__.py +348 -391
  83. pyxllib/prog/specialist/bc.py +203 -203
  84. pyxllib/prog/specialist/browser.py +497 -497
  85. pyxllib/prog/specialist/common.py +347 -347
  86. pyxllib/prog/specialist/datetime.py +198 -198
  87. pyxllib/prog/specialist/tictoc.py +240 -240
  88. pyxllib/prog/specialist/xllog.py +180 -180
  89. pyxllib/prog/xlosenv.py +110 -108
  90. pyxllib/stdlib/__init__.py +17 -17
  91. pyxllib/stdlib/tablepyxl/__init__.py +10 -10
  92. pyxllib/stdlib/tablepyxl/style.py +303 -303
  93. pyxllib/stdlib/tablepyxl/tablepyxl.py +130 -130
  94. pyxllib/text/__init__.py +8 -8
  95. pyxllib/text/ahocorasick.py +36 -39
  96. pyxllib/text/airscript.js +754 -744
  97. pyxllib/text/charclasslib.py +121 -121
  98. pyxllib/text/jiebalib.py +267 -267
  99. pyxllib/text/jinjalib.py +27 -32
  100. pyxllib/text/jsa_ai_prompt.md +271 -271
  101. pyxllib/text/jscode.py +922 -922
  102. pyxllib/text/latex/__init__.py +158 -158
  103. pyxllib/text/levenshtein.py +303 -303
  104. pyxllib/text/nestenv.py +1215 -1215
  105. pyxllib/text/newbie.py +300 -300
  106. pyxllib/text/pupil/__init__.py +8 -8
  107. pyxllib/text/pupil/common.py +1121 -1121
  108. pyxllib/text/pupil/xlalign.py +326 -326
  109. pyxllib/text/pycode.py +47 -47
  110. pyxllib/text/specialist/__init__.py +8 -8
  111. pyxllib/text/specialist/common.py +112 -112
  112. pyxllib/text/specialist/ptag.py +186 -186
  113. pyxllib/text/spellchecker.py +172 -172
  114. pyxllib/text/templates/echart_base.html +10 -10
  115. pyxllib/text/templates/highlight_code.html +16 -16
  116. pyxllib/text/templates/latex_editor.html +102 -102
  117. pyxllib/text/vbacode.py +17 -17
  118. pyxllib/text/xmllib.py +741 -747
  119. pyxllib/xl.py +42 -39
  120. pyxllib/xlcv.py +17 -17
  121. pyxllib-3.201.1.dist-info/METADATA +296 -0
  122. pyxllib-3.201.1.dist-info/RECORD +125 -0
  123. {pyxllib-0.3.197.dist-info → pyxllib-3.201.1.dist-info}/licenses/LICENSE +190 -190
  124. pyxllib/ext/old.py +0 -663
  125. pyxllib-0.3.197.dist-info/METADATA +0 -48
  126. pyxllib-0.3.197.dist-info/RECORD +0 -126
  127. {pyxllib-0.3.197.dist-info → pyxllib-3.201.1.dist-info}/WHEEL +0 -0
@@ -1,67 +1,67 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- # @Author : 陈坤泽
4
- # @Email : 877362867@qq.com
5
- # @Date : 2021/06/23 11:26
6
-
7
- import subprocess
8
- import re
9
- import numpy as np
10
-
11
- try:
12
- import shapely
13
- except ModuleNotFoundError:
14
- try:
15
- subprocess.run(['conda', 'install', 'shapely'])
16
- import shapely
17
- except FileNotFoundError:
18
- # 这个库用pip安装是不够的,正常要用conda,有些dll才会自动配置上
19
- subprocess.run(['pip3', 'install', 'shapely'])
20
- import shapely
21
-
22
- from shapely.geometry import Polygon
23
-
24
- from pyxllib.algo.geo import rect2polygon
25
-
26
-
27
- class ShapelyPolygon:
28
- @classmethod
29
- def gen(cls, x):
30
- """ 转成shapely的Polygon对象
31
-
32
- :param x: 支持多种格式,详见代码
33
- :return: Polygon
34
-
35
- >>> print(ShapelyPolygon.gen([[0, 0], [10, 20]])) # list
36
- POLYGON ((0 0, 10 0, 10 20, 0 20, 0 0))
37
- >>> print(ShapelyPolygon.gen({'shape_type': 'polygon', 'points': [[0, 0], [10, 0], [10, 20], [0, 20]]})) # labelme shape
38
- POLYGON ((0 0, 10 0, 10 20, 0 20, 0 0))
39
- >>> print(ShapelyPolygon.gen('107,247,2358,209,2358,297,107,335')) # 字符串格式
40
- POLYGON ((107 247, 2358 209, 2358 297, 107 335, 107 247))
41
- >>> print(ShapelyPolygon.gen('107 247.5, 2358 209.2, 2358 297, 107.5 335')) # 字符串格式
42
- POLYGON ((107 247.5, 2358 209.2, 2358 297, 107.5 335, 107 247.5))
43
- """
44
- if isinstance(x, Polygon):
45
- return x
46
- elif isinstance(x, dict) and 'points' in x:
47
- if x['shape_type'] in ('rectangle', 'polygon'):
48
- # 目前这种情况一般是输入了labelme的shape格式
49
- return ShapelyPolygon.gen(x['points'])
50
- else:
51
- raise ValueError('无法转成多边形的类型')
52
- elif isinstance(x, str):
53
- coords = re.findall(r'[\d\.]+', x)
54
- return ShapelyPolygon.gen(coords)
55
- else:
56
- x = np.array(x).reshape((-1, 2))
57
- if x.shape[0] == 2:
58
- x = rect2polygon(x)
59
- x = np.array(x)
60
- if x.shape[0] >= 3:
61
- return Polygon(x)
62
- else:
63
- raise ValueError
64
-
65
- @classmethod
66
- def to_ndarray(cls, p, dtype=None):
67
- return np.array(p.exterior.coords, dtype=dtype)
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # @Author : 陈坤泽
4
+ # @Email : 877362867@qq.com
5
+ # @Date : 2021/06/23 11:26
6
+
7
+ import subprocess
8
+ import re
9
+ import numpy as np
10
+
11
+ try:
12
+ import shapely
13
+ except ModuleNotFoundError:
14
+ try:
15
+ subprocess.run(['conda', 'install', 'shapely'])
16
+ import shapely
17
+ except FileNotFoundError:
18
+ # 这个库用pip安装是不够的,正常要用conda,有些dll才会自动配置上
19
+ subprocess.run(['pip3', 'install', 'shapely'])
20
+ import shapely
21
+
22
+ from shapely.geometry import Polygon
23
+
24
+ from pyxllib.algo.geo import rect2polygon
25
+
26
+
27
+ class ShapelyPolygon:
28
+ @classmethod
29
+ def gen(cls, x):
30
+ """ 转成shapely的Polygon对象
31
+
32
+ :param x: 支持多种格式,详见代码
33
+ :return: Polygon
34
+
35
+ >>> print(ShapelyPolygon.gen([[0, 0], [10, 20]])) # list
36
+ POLYGON ((0 0, 10 0, 10 20, 0 20, 0 0))
37
+ >>> print(ShapelyPolygon.gen({'shape_type': 'polygon', 'points': [[0, 0], [10, 0], [10, 20], [0, 20]]})) # labelme shape
38
+ POLYGON ((0 0, 10 0, 10 20, 0 20, 0 0))
39
+ >>> print(ShapelyPolygon.gen('107,247,2358,209,2358,297,107,335')) # 字符串格式
40
+ POLYGON ((107 247, 2358 209, 2358 297, 107 335, 107 247))
41
+ >>> print(ShapelyPolygon.gen('107 247.5, 2358 209.2, 2358 297, 107.5 335')) # 字符串格式
42
+ POLYGON ((107 247.5, 2358 209.2, 2358 297, 107.5 335, 107 247.5))
43
+ """
44
+ if isinstance(x, Polygon):
45
+ return x
46
+ elif isinstance(x, dict) and 'points' in x:
47
+ if x['shape_type'] in ('rectangle', 'polygon'):
48
+ # 目前这种情况一般是输入了labelme的shape格式
49
+ return ShapelyPolygon.gen(x['points'])
50
+ else:
51
+ raise ValueError('无法转成多边形的类型')
52
+ elif isinstance(x, str):
53
+ coords = re.findall(r'[\d\.]+', x)
54
+ return ShapelyPolygon.gen(coords)
55
+ else:
56
+ x = np.array(x).reshape((-1, 2))
57
+ if x.shape[0] == 2:
58
+ x = rect2polygon(x)
59
+ x = np.array(x)
60
+ if x.shape[0] >= 3:
61
+ return Polygon(x)
62
+ else:
63
+ raise ValueError
64
+
65
+ @classmethod
66
+ def to_ndarray(cls, p, dtype=None):
67
+ return np.array(p.exterior.coords, dtype=dtype)
@@ -1,241 +1,241 @@
1
- #!/usr/bin/env python3
2
- # -*- coding: utf-8 -*-
3
- # @Author : 陈坤泽
4
- # @Email : 877362867@qq.com
5
- # @Date : 2021/06/06 11:16
6
-
7
- import copy
8
- import itertools
9
-
10
- import numpy as np
11
- import pandas as pd
12
-
13
- from pyxllib.prog.pupil import DictTool
14
- # from pyxllib.prog.deprecatedlib import deprecated
15
- from deprecated import deprecated
16
-
17
-
18
- @deprecated(reason='这个实现方式不佳,请参考 make_index_function')
19
- def sort_by_given_list(a, b):
20
- r""" 本函数一般用在数据透视表中,分组中元素名为中文,没有按指定规律排序的情况
21
-
22
- :param a: 需要排序的对象
23
- :param b: 参照的排序数组
24
- :return: 排序后的a
25
-
26
- >>> sort_by_given_list(['初中', '小学', '高中'], ['少儿', '小学', '初中', '高中'])
27
- ['小学', '初中', '高中']
28
-
29
- # 不在枚举项目里的,会统一列在最后面
30
- >>> sort_by_given_list(['初中', '小学', '高中', '幼儿'], ['少儿', '小学', '初中', '高中'])
31
- ['小学', '初中', '高中', '幼儿']
32
- """
33
- # 1 从b数组构造一个d字典,d[k]=i,值为k的元素在第i位
34
- d = dict()
35
- for i, bb in enumerate(b): d[bb] = i
36
- # 2 a数组分两部分,可以通过d排序的a1,和不能通过d排序的a2
37
- a1, a2 = [], []
38
- for aa in a:
39
- if aa in d:
40
- a1.append(aa)
41
- else:
42
- a2.append(aa)
43
- # 3 用不同的规则排序a1、a2后合并
44
- a1 = sorted(a1, key=lambda x: d[x])
45
- a2 = sorted(a2)
46
- return a1 + a2
47
-
48
-
49
- def product(*iterables, order=None, repeat=1):
50
- """ 对 itertools 的product扩展orders参数的更高级的product迭代器
51
-
52
- :param order: 假设iterables有n=3个迭代器,则默认 orders=[1, 2, 3] (起始编号1)
53
- 即标准的product,是按顺序对每个迭代器进行重置、遍历的
54
- 但是我扩展的这个接口,允许调整每个维度的更新顺序
55
- 例如设置为 [-2, 1, 3],表示先对第2维降序,然后按第1、3维的方式排序获得各个坐标点
56
- 注:可以只输入[-2],默认会自动补充维[1, 3]
57
-
58
- 不从0开始编号,是因为0没法记录正负排序情况
59
-
60
- for x in product('ab', 'cd', 'ef', order=[3, -2, 1]):
61
- print(x)
62
-
63
- ['a', 'd', 'e']
64
- ['b', 'd', 'e']
65
- ['a', 'c', 'e']
66
- ['b', 'c', 'e']
67
- ['a', 'd', 'f']
68
- ['b', 'd', 'f']
69
- ['a', 'c', 'f']
70
- ['b', 'c', 'f']
71
-
72
- TODO 我在想numpy这么牛逼,会不会有等价的功能接口可以实现,我不用重复造轮子?
73
- """
74
- # 一、标准调用方式
75
- if order is None:
76
- for x in itertools.product(*iterables, repeat=repeat):
77
- yield x
78
- return
79
-
80
- # 二、输入orders参数的调用方式
81
- # 1 补全orders参数长度
82
- n = len(iterables)
83
- for i in range(1, n + 1):
84
- if not (i in order or -i in order):
85
- order.append(i)
86
- if len(order) != n: return ValueError(f'orders参数值有问题 {order}')
87
-
88
- # 2 生成新的迭代器组
89
- new_iterables = [(iterables[i - 1] if i > 0 else reversed(iterables[-i - 1])) for i in order]
90
- idx = np.argsort([abs(i) - 1 for i in order])
91
- for y in itertools.product(*new_iterables, repeat=repeat):
92
- yield [y[i] for i in idx]
93
-
94
-
95
- class MatchPairs:
96
- """ 匹配类,对X,Y两组数据中的x,y等对象按照cmp_func的规则进行相似度配对
97
-
98
- MatchBase(ys, cmp_func).matches(xs, least_score)
99
- """
100
-
101
- def __init__(self, ys, cmp_func):
102
- self.ys = list(ys)
103
- self.cmp_func = cmp_func
104
-
105
- def __getitem__(self, idx):
106
- return self.ys[idx]
107
-
108
- # def __del__(self, idx):
109
- # del self.ys[idx]
110
-
111
- def __len__(self):
112
- return len(self.ys)
113
-
114
- def match(self, x, k=1):
115
- """ 匹配一个对象
116
-
117
- :param x: 待匹配的一个对象
118
- :param k: 返回次优的几个结果
119
- :return:
120
- 当 k = 1 时,返回 (idx, score)
121
- 当 k > 1 时,返回 [(idx1, score1), (idx2, score2), ...]
122
- """
123
- scores = [self.cmp_func(x, y) for y in self.ys]
124
- if k == 1:
125
- score = max(scores)
126
- idx = scores.index(score)
127
- return idx, score
128
- else:
129
- # 按权重从大到小排序
130
- idxs = np.argsort(scores)
131
- idxs = idxs[::-1][:k]
132
- return [(idx, scores[idx]) for idx in idxs]
133
-
134
- def matches(self, xs):
135
- """ 对xs中每个元素都找到一个最佳匹配对象
136
-
137
- 注意:这个功能是支持ys中的元素被重复匹配的,而且哪怕相似度很低,也会返回一个最佳匹配结果
138
- 如果想限定相似度,或者不支持重复匹配,请到隔壁使用 matchpairs
139
-
140
- :param xs: 要匹配的一组对象
141
- :return: 为每个x找到一个最佳的匹配y,存储其下标和对应的分值
142
- [(idx0, score0), (idx1, score1), ...] 长度 = len(xs)
143
-
144
- >>> m = MatchPairs([1, 5, 8, 9, 2], lambda x,y: 1-abs(x-y)/max(x,y))
145
- >>> m.matches([4, 6]) # 这里第1个值是下标,所以分别是对应5、8
146
- [(1, 0.8), (1, 0.8333333333333334)]
147
-
148
- # 要匹配的对象多于实际ys,则只会返回前len(ys)个结果
149
- # 这种情况建议用matchpairs功能实现,或者实在想用就对调xs、ys
150
- >>> m.matches([4, 6, 1, 2, 9, 4, 5])
151
- [(1, 0.8), (1, 0.8333333333333334), (0, 1.0), (4, 1.0), (3, 1.0), (1, 0.8), (1, 1.0)]
152
- """
153
- return [self.match(x) for x in xs]
154
-
155
-
156
- def get_ndim(coords):
157
- # 注意 np.array(coords[:1]),只需要取第一个元素就可以判断出ndim
158
- coords = coords if isinstance(coords, np.ndarray) else np.array(coords[:1])
159
- return coords.ndim
160
-
161
-
162
- class DictCmper:
163
- """ 字典结构比较工具
164
-
165
- 集合是字典的特殊情况,也支持集合间的对比
166
- """
167
-
168
- def __init__(self, dicts):
169
- """
170
- :param Dict[str, Dict|set] dicts: Dicts[dictname, dict_]
171
- 如果是set,会升级为dict,value默认为1
172
- """
173
- self.dicts = {}
174
- for k, v in dicts.items():
175
- if isinstance(v, set):
176
- self.dicts[k] = {k: 1 for k in v}
177
- else:
178
- self.dicts[k] = v
179
-
180
- def details(self):
181
- """ 返回详细的分析表
182
-
183
- 按行罗列所有键,按列罗列所有字典,中间显示各字典键值
184
- 可以把结果保存到excel,然后详细筛选分析
185
-
186
- >>> dc = DictCmper({'d1': {'a': 1, 'b': 2}, 'd2': {'b': 3, 'e': 5}, 'd3': {'d': 4}})
187
- >>> dc.details()
188
- d1 d2 d3
189
- a 1.0 NaN NaN
190
- b 2.0 3.0 NaN
191
- e NaN 5.0 NaN
192
- d NaN NaN 4.0
193
- """
194
- # 1 获得所有键
195
- # 集合无法保存元素顺序,所以用合并字典来代替
196
- # 还有个三方库orderedset,不想安装。就这样简便解决就好。
197
- keys = DictTool.or_(*self.dicts.values()).keys()
198
-
199
- # 2 取出所有字典值
200
- ls = []
201
- for k in keys:
202
- ls.append([(d[k] if k in d else np.nan) for d in self.dicts.values()])
203
-
204
- # 3 转为df表格
205
- df = pd.DataFrame.from_records(ls, columns=self.dicts.keys())
206
- df.index = keys
207
- return df
208
-
209
- def pair_summary(self, func=lambda x, y: len(x.keys() & y.keys())):
210
- r""" 两两对比表
211
-
212
- :param func: 默认是计算两个字典共有的键数量
213
- :return: df
214
- df对角线存储的是每个集合自身大小,df第i行第j列是第i个集合减去第j个集合的剩余元素数
215
-
216
- >>> s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
217
- >>> s2 = {1, 3, 5, 7, 8}
218
- >>> s3 = {2, 3, 5, 8}
219
- >>> dc = DictCmper({'s1': s1, 's2': s2, 's3': s3})
220
- >>> dc.pair_summary()
221
- s1 s2 s3
222
- s1 9 5 4
223
- s2 5 5 3
224
- s3 4 3 4
225
- >>> dc.pair_summary(lambda x, y: len(x.keys() - y.keys()))
226
- s1 s2 s3
227
- s1 0 4 5
228
- s2 0 0 2
229
- s3 0 1 0
230
- """
231
- dictnames = list(self.dicts.keys())
232
- n = len(dictnames)
233
- rows = []
234
- for i, name1 in enumerate(dictnames):
235
- row = [0] * n
236
- for j, name2 in enumerate(dictnames):
237
- row[j] = func(self.dicts[name1], self.dicts[name2])
238
- rows.append(row)
239
- df = pd.DataFrame.from_records(rows, columns=dictnames)
240
- df.index = dictnames
241
- return df
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ # @Author : 陈坤泽
4
+ # @Email : 877362867@qq.com
5
+ # @Date : 2021/06/06 11:16
6
+
7
+ import copy
8
+ import itertools
9
+
10
+ import numpy as np
11
+ import pandas as pd
12
+
13
+ from pyxllib.prog.pupil import DictTool
14
+ # from pyxllib.prog.deprecatedlib import deprecated
15
+ from deprecated import deprecated
16
+
17
+
18
+ @deprecated(reason='这个实现方式不佳,请参考 make_index_function')
19
+ def sort_by_given_list(a, b):
20
+ r""" 本函数一般用在数据透视表中,分组中元素名为中文,没有按指定规律排序的情况
21
+
22
+ :param a: 需要排序的对象
23
+ :param b: 参照的排序数组
24
+ :return: 排序后的a
25
+
26
+ >>> sort_by_given_list(['初中', '小学', '高中'], ['少儿', '小学', '初中', '高中'])
27
+ ['小学', '初中', '高中']
28
+
29
+ # 不在枚举项目里的,会统一列在最后面
30
+ >>> sort_by_given_list(['初中', '小学', '高中', '幼儿'], ['少儿', '小学', '初中', '高中'])
31
+ ['小学', '初中', '高中', '幼儿']
32
+ """
33
+ # 1 从b数组构造一个d字典,d[k]=i,值为k的元素在第i位
34
+ d = dict()
35
+ for i, bb in enumerate(b): d[bb] = i
36
+ # 2 a数组分两部分,可以通过d排序的a1,和不能通过d排序的a2
37
+ a1, a2 = [], []
38
+ for aa in a:
39
+ if aa in d:
40
+ a1.append(aa)
41
+ else:
42
+ a2.append(aa)
43
+ # 3 用不同的规则排序a1、a2后合并
44
+ a1 = sorted(a1, key=lambda x: d[x])
45
+ a2 = sorted(a2)
46
+ return a1 + a2
47
+
48
+
49
+ def product(*iterables, order=None, repeat=1):
50
+ """ 对 itertools 的product扩展orders参数的更高级的product迭代器
51
+
52
+ :param order: 假设iterables有n=3个迭代器,则默认 orders=[1, 2, 3] (起始编号1)
53
+ 即标准的product,是按顺序对每个迭代器进行重置、遍历的
54
+ 但是我扩展的这个接口,允许调整每个维度的更新顺序
55
+ 例如设置为 [-2, 1, 3],表示先对第2维降序,然后按第1、3维的方式排序获得各个坐标点
56
+ 注:可以只输入[-2],默认会自动补充维[1, 3]
57
+
58
+ 不从0开始编号,是因为0没法记录正负排序情况
59
+
60
+ for x in product('ab', 'cd', 'ef', order=[3, -2, 1]):
61
+ print(x)
62
+
63
+ ['a', 'd', 'e']
64
+ ['b', 'd', 'e']
65
+ ['a', 'c', 'e']
66
+ ['b', 'c', 'e']
67
+ ['a', 'd', 'f']
68
+ ['b', 'd', 'f']
69
+ ['a', 'c', 'f']
70
+ ['b', 'c', 'f']
71
+
72
+ TODO 我在想numpy这么牛逼,会不会有等价的功能接口可以实现,我不用重复造轮子?
73
+ """
74
+ # 一、标准调用方式
75
+ if order is None:
76
+ for x in itertools.product(*iterables, repeat=repeat):
77
+ yield x
78
+ return
79
+
80
+ # 二、输入orders参数的调用方式
81
+ # 1 补全orders参数长度
82
+ n = len(iterables)
83
+ for i in range(1, n + 1):
84
+ if not (i in order or -i in order):
85
+ order.append(i)
86
+ if len(order) != n: return ValueError(f'orders参数值有问题 {order}')
87
+
88
+ # 2 生成新的迭代器组
89
+ new_iterables = [(iterables[i - 1] if i > 0 else reversed(iterables[-i - 1])) for i in order]
90
+ idx = np.argsort([abs(i) - 1 for i in order])
91
+ for y in itertools.product(*new_iterables, repeat=repeat):
92
+ yield [y[i] for i in idx]
93
+
94
+
95
+ class MatchPairs:
96
+ """ 匹配类,对X,Y两组数据中的x,y等对象按照cmp_func的规则进行相似度配对
97
+
98
+ MatchBase(ys, cmp_func).matches(xs, least_score)
99
+ """
100
+
101
+ def __init__(self, ys, cmp_func):
102
+ self.ys = list(ys)
103
+ self.cmp_func = cmp_func
104
+
105
+ def __getitem__(self, idx):
106
+ return self.ys[idx]
107
+
108
+ # def __del__(self, idx):
109
+ # del self.ys[idx]
110
+
111
+ def __len__(self):
112
+ return len(self.ys)
113
+
114
+ def match(self, x, k=1):
115
+ """ 匹配一个对象
116
+
117
+ :param x: 待匹配的一个对象
118
+ :param k: 返回次优的几个结果
119
+ :return:
120
+ 当 k = 1 时,返回 (idx, score)
121
+ 当 k > 1 时,返回 [(idx1, score1), (idx2, score2), ...]
122
+ """
123
+ scores = [self.cmp_func(x, y) for y in self.ys]
124
+ if k == 1:
125
+ score = max(scores)
126
+ idx = scores.index(score)
127
+ return idx, score
128
+ else:
129
+ # 按权重从大到小排序
130
+ idxs = np.argsort(scores)
131
+ idxs = idxs[::-1][:k]
132
+ return [(idx, scores[idx]) for idx in idxs]
133
+
134
+ def matches(self, xs):
135
+ """ 对xs中每个元素都找到一个最佳匹配对象
136
+
137
+ 注意:这个功能是支持ys中的元素被重复匹配的,而且哪怕相似度很低,也会返回一个最佳匹配结果
138
+ 如果想限定相似度,或者不支持重复匹配,请到隔壁使用 matchpairs
139
+
140
+ :param xs: 要匹配的一组对象
141
+ :return: 为每个x找到一个最佳的匹配y,存储其下标和对应的分值
142
+ [(idx0, score0), (idx1, score1), ...] 长度 = len(xs)
143
+
144
+ >>> m = MatchPairs([1, 5, 8, 9, 2], lambda x,y: 1-abs(x-y)/max(x,y))
145
+ >>> m.matches([4, 6]) # 这里第1个值是下标,所以分别是对应5、8
146
+ [(1, 0.8), (1, 0.8333333333333334)]
147
+
148
+ # 要匹配的对象多于实际ys,则只会返回前len(ys)个结果
149
+ # 这种情况建议用matchpairs功能实现,或者实在想用就对调xs、ys
150
+ >>> m.matches([4, 6, 1, 2, 9, 4, 5])
151
+ [(1, 0.8), (1, 0.8333333333333334), (0, 1.0), (4, 1.0), (3, 1.0), (1, 0.8), (1, 1.0)]
152
+ """
153
+ return [self.match(x) for x in xs]
154
+
155
+
156
+ def get_ndim(coords):
157
+ # 注意 np.array(coords[:1]),只需要取第一个元素就可以判断出ndim
158
+ coords = coords if isinstance(coords, np.ndarray) else np.array(coords[:1])
159
+ return coords.ndim
160
+
161
+
162
+ class DictCmper:
163
+ """ 字典结构比较工具
164
+
165
+ 集合是字典的特殊情况,也支持集合间的对比
166
+ """
167
+
168
+ def __init__(self, dicts):
169
+ """
170
+ :param Dict[str, Dict|set] dicts: Dicts[dictname, dict_]
171
+ 如果是set,会升级为dict,value默认为1
172
+ """
173
+ self.dicts = {}
174
+ for k, v in dicts.items():
175
+ if isinstance(v, set):
176
+ self.dicts[k] = {k: 1 for k in v}
177
+ else:
178
+ self.dicts[k] = v
179
+
180
+ def details(self):
181
+ """ 返回详细的分析表
182
+
183
+ 按行罗列所有键,按列罗列所有字典,中间显示各字典键值
184
+ 可以把结果保存到excel,然后详细筛选分析
185
+
186
+ >>> dc = DictCmper({'d1': {'a': 1, 'b': 2}, 'd2': {'b': 3, 'e': 5}, 'd3': {'d': 4}})
187
+ >>> dc.details()
188
+ d1 d2 d3
189
+ a 1.0 NaN NaN
190
+ b 2.0 3.0 NaN
191
+ e NaN 5.0 NaN
192
+ d NaN NaN 4.0
193
+ """
194
+ # 1 获得所有键
195
+ # 集合无法保存元素顺序,所以用合并字典来代替
196
+ # 还有个三方库orderedset,不想安装。就这样简便解决就好。
197
+ keys = DictTool.or_(*self.dicts.values()).keys()
198
+
199
+ # 2 取出所有字典值
200
+ ls = []
201
+ for k in keys:
202
+ ls.append([(d[k] if k in d else np.nan) for d in self.dicts.values()])
203
+
204
+ # 3 转为df表格
205
+ df = pd.DataFrame.from_records(ls, columns=self.dicts.keys())
206
+ df.index = keys
207
+ return df
208
+
209
+ def pair_summary(self, func=lambda x, y: len(x.keys() & y.keys())):
210
+ r""" 两两对比表
211
+
212
+ :param func: 默认是计算两个字典共有的键数量
213
+ :return: df
214
+ df对角线存储的是每个集合自身大小,df第i行第j列是第i个集合减去第j个集合的剩余元素数
215
+
216
+ >>> s1 = {1, 2, 3, 4, 5, 6, 7, 8, 9}
217
+ >>> s2 = {1, 3, 5, 7, 8}
218
+ >>> s3 = {2, 3, 5, 8}
219
+ >>> dc = DictCmper({'s1': s1, 's2': s2, 's3': s3})
220
+ >>> dc.pair_summary()
221
+ s1 s2 s3
222
+ s1 9 5 4
223
+ s2 5 5 3
224
+ s3 4 3 4
225
+ >>> dc.pair_summary(lambda x, y: len(x.keys() - y.keys()))
226
+ s1 s2 s3
227
+ s1 0 4 5
228
+ s2 0 0 2
229
+ s3 0 1 0
230
+ """
231
+ dictnames = list(self.dicts.keys())
232
+ n = len(dictnames)
233
+ rows = []
234
+ for i, name1 in enumerate(dictnames):
235
+ row = [0] * n
236
+ for j, name2 in enumerate(dictnames):
237
+ row[j] = func(self.dicts[name1], self.dicts[name2])
238
+ rows.append(row)
239
+ df = pd.DataFrame.from_records(rows, columns=dictnames)
240
+ df.index = dictnames
241
+ return df