-
Notifications
You must be signed in to change notification settings - Fork 0
/
T.py
executable file
·2642 lines (2279 loc) · 86.9 KB
/
T.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
863
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# coding=utf-8
#考虑qgb 位于另一个包内的情况
if __name__.endswith('qgb.T'):from . import py
else:#['T','__main__']
import py
FILE_NAME=fileChars=FILE_CHARS="!#$%&'() ,-0123456789;=@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_`abcdefghijklmnopqrstuvwxyz{}~" ' .'
PATH_NAME=pathChars=PATH_CHARS='/\\:' FILE_NAME# include space, dot
gsNOT_FILE_NAME_WINDOWS=gsNOT_FILE_NAME=NOT_FILE_NAME_WINDOWS=NOT_FILE_NAME=r'"*/:<>?\|'
gsNOT_PATH_NAME_WINDOWS=gsNOT_PATH_NAME=NOT_PATH_NAME_WINDOWS=NOT_PATH_NAME=r'"*<>?|' # : is
gsNOT_FILE_NAME_LINUX=NOT_FILE_NAME_LINUX='/' py.chr(92) # \ chr(0x5C)
az=a_z='abcdefghijklmnopqrstuvwxyz'
AZ=A_Z=a_z.upper()
alphabet=alphabeT=azAZ=aZ=a_Z=a_z A_Z # The English Alphabet Has 52 Letters
Alphabet=AZaz=Az=A_z=A_Z a_z
character=aZ=azAZ###Do not Change
num=s09=_09=number='0123456789'
_10='1234567890'
azAZ09=aZ09=a_Z0_9=alphanumeric=character number#azAZ09, not gs09AZ
aZ09_=_aZ09=_alphanumeric=alphanumeric_=alphanumeric '_'
Az09=A_z0_9=A_Z a_z number
Hex=gshex='0123456789abcdef'
HEX=gshex.upper()
#0x20-0x7E ,32-126,len=95
visAscii=print_ascii=printAscii=asciiPrint=' !"#$%&\'()* ,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~'
gs256=char256=''.join([py.chr(i) for i in range(256)])
bytes256_list=byte256_list=[py.byte(i) for i in range(256) ]
bytes256=byte256=b''.join( bytes256_list )
CR='\r'
LF=EOL=eol='\n'
EOLS=EOL '='*44 EOL
CRLF='\r\n'
TAB=Tab=tab='\t'
gspace=space=py.chr(0x20)
slash='/' # chr(0x2F)
back_slash=backslash='\\' # chr(0x5C)
eq=equal=EQ='='
black=blackblock='\u2B1B' # ⬛
star=asterisk=ASTERISK='*'
######### html ######
hr='<hr>'
br='<br>'
u23=s23='#-'
p23='#-'
#######################
RE_IMG_URL=r'(((http://www)|(http://)|(www))[-a-zA-Z0-9@:%_\ .~#?&//=] )\.(jpg|jpeg|gif|png|bmp|tiff|tga|svg)'
RE_URL=r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.& ]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F])) '
RE_YMD=r"(19|20)[0-9]{2}[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])"
RE_WhiteSpace=r'\s '
RE_VAR_SIMPLE=RE_VAR=RE_variable_name=RE_python_variable_name=r'[_a-zA-Z]\w*'#
#\w(不是W) 一共有 127073个字符,其中有815个不在sv中。sv一共有128491个非空字符。2233个不在\w中。交集有 126258个
#如果不小心用(注意大小写)A-z Matches a character in the range "A" to "z" (char code 65 to 122). Case sensitive.
RE_VARS_COMMAS=RE_vars_separated_by_commas=r'VAR(?:\s*,\s*VAR) '.replace('VAR',RE_VAR)
RE_GIT_REPO_URL=RE_GIT_REPO=r'((?P<protocol>git|ssh|http(s)?)|(git@[\w\.] ))(:(\/\/)?)(?P<netloc>[\w\@\.\:~] )\/(?P<user>[\w\-] )\/(?P<repo>[\w\-\.] (\.git)?)'
RE_GIT=RE_GIT_URL=RE_URL_GIT=RE_GIT_REPO_OTHER=RE_GIT_REPO '(?P<other>[\w\/]*)'
RE_FLOAT=REF=r'[ -]?([0-9]*[.])?[0-9] '
###############
SQLITE='SELECT * FROM sqlite_master;'
#########################################
dyh=squote=quote="'"
syh=double_quote=dquote=dQuote='"'
import re
IGNORECASE=re_IGNORECASE=re.IGNORECASE
gError=None
try:
try :from cchardet import detect as _detect
except:from chardet import detect as _detect
def detect(abytes,confidence=0.7,default=py.No('default encoding "" ') ):
'''
T._detect( b'\x1b'*1) ### {'encoding': None, 'confidence': 0.0, 'language': None}
_detect 可能返回 {'encoding': None, 'confidence': None}
'''
r=_detect(abytes)
if r['encoding'] in ['Windows-1254' ]:
try:
if abytes.decode('utf-8').encode('utf-8')==abytes:
return 'utf-8'
except Exception as e:
pass
if r['encoding'] in ['gb2312','GB2312' ]:
try:
if abytes.decode('gb18030').encode('gb18030')==abytes:
return 'gb18030'
except Exception as e:
pass
if r['confidence'] and r['confidence']>confidence:return r['encoding']
else:
if default:return default
# raise Exception
return py.No(abytes,r,msg=
'T.detect encoding {1} confidence {2} less then {3} {0}'.format(
py.len(abytes),r['encoding'],r['confidence'],confidence) )
except Exception as ei:
def detect(*a):
raise Exception('#not install chardet Module') # <no> is not callable ,see the source
pass
try:
from io import StringIO
strio=StrIO=stringIO=StringIO
from pprint import pprint,pformat
except:pass
####################################################
def uncurl(sc=''):
import uncurl
U,T,N,F=py.importUTNF()
if not sc:sc=U.cbg()
rs=uncurl.parse(sc)
return U.StrRepr(rs)
def list_append_row_StrRepr(alist,**ka):
global U,T,N,F
U,T,N,F=py.importUTNF()
row=[]
for k,v in ka.items():
if py.len(k)<2:raise py.NotImplementedError()
n=py.int(k[1:])
row.append(U.StrRepr(v,size=n))
alist.append(row)
append=list_append_row_StrRepr
def parse_requirements_txt(f):
'''C:\test\github\TradingView-Machine-Learning-GUI\requirements.txt
'''
global U,T,N,F
U,T,N,F=py.importUTNF()
d={}
for line in F.readlines(f):
line=line.strip()
if not line:continue
if '==' in line:
name,v=line.split('==')
else:
name,v=line,None
d[name]=v
# r.append(line)
return d
def ip_to_hex(ip,splitor=""):
return splitor.join(map(str,["{0:02x}".format(int(x)) for x in ip.split(".")]))
ip2h=ip2hex=ip_to_hex
def ip_to_binary(ip,splitor="."):
return splitor.join(map(str,["{0:08b}".format(int(x)) for x in ip.split(".")]))
ip2b=ip2bin=ip_to_bin=ip_to_binary
def parse_http_plain_request(t):
import email,io
message=email.message_from_file(io.StringIO(t))
return py.dict(message.items())
parse_HTTPAnalyzer_request=parse_http_plain_request
def parse_WebKitFormBoundary(a,content_type=py.No('auto')):
'''
[[0, '__class__', requests_toolbelt.multipart.decoder.BodyPart],
[1, '__delattr__', <method-wrapper '__delattr__' of BodyPart object at 0x000002B990690EC8>],
[2, '__dict__', {'encoding': 'utf-8', 'content': b'8000000', 'headers': {b'Content-Disposition': b'form-data; name="MAX_FILE_SIZE"'}}],
[3, '__dir__', <function BodyPart.__dir__()>],
[4,
'__doc__',
'\n\n The ``BodyPart`` object is a ``Response``-like interface to an individual\n subpart of a multipart response. It is expected that these will\n generally be created by objects of the ``MultipartDecoder`` class.\n\n Like ``Response``, there is a ``CaseInsensitiveDict`` object named headers,\n ``content`` to access bytes, ``text`` to access unicode, and ``encoding``\n to access the unicode codec.\n\n '],
....
[26, 'content', b'8000000'],
[27, 'encoding', 'utf-8'],
[28, 'headers', {b'Content-Disposition': b'form-data; name="MAX_FILE_SIZE"'}],
[29, 'text', '8000000']]
'''
from requests_toolbelt.multipart import decoder
# a = b"--ce560532019a77d83195f9e9873e16a1\r\nContent-Disposition: form-data; name=\"author\"\r\n\r\nJohn Smith\r\n--ce560532019a77d83195f9e9873e16a1\r\nContent-Disposition: form-data; name=\"file\"; filename=\"example2.txt\"\r\nContent-Type: text/plain\r\nExpires: 0\r\n\r\nHello World\r\n--ce560532019a77d83195f9e9873e16a1--\r\n"
# content_type = "multipart/form-data; boundary=ce560532019a77d83195f9e9873e16a1"
# content_type = 'multipart/form-data; boundary=----WebKitFormBoundaryZXuC4Jc1YZng6box'
if py.istr(a):
a=a.encode()
if not content_type:
h=a.splitlines()[0].decode().strip()[2:]
content_type= fr'multipart/form-data; boundary={h}'
r=[]
for part in decoder.MultipartDecoder(a, content_type).parts:
print(part.text)
r.append(part)
# return a,content_type,r
return r
MultipartDecoder=parse_WebKitFormBoundary
def xml_to_dict(sxml):
import xmltodict
return xmltodict.parse(sxml)
# =xml_to_json
xmltodict=xml_to_dict
def extract_UTNF_function(f):
global U,T,N,F
U,T,N,F=py.importUTNF()
def chr(*a):
if py.len(a)==1 and not py.isint(a[0]):
a=a[0]
if py.len(a)==1 and a[0]> 0x110000:
s=py.hex(a[0])[2:]
ms=py.len(s)
if ms%2!=0:raise py.ArgumentError('0xAABBCC long a % 2 ! 0 ')
ta=[]
for i in py.range(0,ms,2):
i=py.int('0x' s[i:i 2],16)
ta.append(i)
a=ta
s=''
for i in a:
s =py.chr(i)
return s
def ord(s,hex=False,_0x='0x'):
global U,T,N,F
U,T,N,F=py.importUTNF()
r=[]
for c in s:
i=py.ord(c)
if hex:
i=U.IntRepr(i,repr=_0x py.hex(i)[2:].upper(),)
r.append(i)
return r
def get_char_name(c):
import unicodedata
r=[]
for i in c:
r.append(unicodedata.name(c))
if py.len(c)==1:
return r[0]
else:
return r
char_name=ascii_name=unicode_name=get_char_name
def pdf_to_text_generator(filename_or_url,**ka):
r''' pip install PyPDF2
AttributeError: function/symbol 'ARC4_stream_init' not found in library 'C:\QGB\Anaconda3\lib\site-packages\Crypto\Util\..\Cipher\_ARC4.cp37-win_amd64.pyd': error 0x7f
https://github.com/py-pdf/PyPDF2/issues/1192
'''
if '://' in filename_or_url:
U,T,N,F=py.importUTNF()
filename=N.HTTP.get_bytes(filename_or_url,return_only_filename=True,skip_if_exist=True,print_req=True,**ka) #if file exist, no print_req
else:
filename=filename_or_url
import PyPDF2
reader=PyPDF2.PdfReader(filename)
# text = ""
for page in reader.pages:
# text = page.extract_text() "\n"
yield page.extract_text() # page_splitor
return
pdf2text_gen=pdf_to_text_gen=pdf_to_text_generator
def pdf_to_text(filename,page_splitor='\n'):
return page_splitor.join(pdf_to_text_generator(filename))
pdf2txt=pdf2text=pdf_to_txt=pdf_to_text
def zh_convert(a,lang='zh-cn'):
''' zh-cn 大陆简体; zh-tw 台灣正體; zh-hk 香港繁體
u'元旦快樂'
'''
from zhconv import convert
return convert(a, lang)
zhc=zhconv=zh_convert
def replace_one(a,old,new):
return a.replace(old, new,1) #count=1 #TypeError: replace() takes no keyword arguments
replaceOnce=replace_one
def get_most_common_substring(str_list):
import operator
return max(substring_counts(str_list).items(), key=operator.itemgetter(1))[0]
most_common_substring=get_most_common_substring
def substring_counts(names):
''' one str list return {}
'''
from difflib import SequenceMatcher
substring_counts={}
for i,s in py.enumerate(names):
for j in range(i 1,len(names)):
string1 = names[i]
string2 = names[j]
match = SequenceMatcher(None, string1, string2).find_longest_match(0, len(string1), 0, len(string2))
matching_substring=string1[match.a:match.a match.size]
if(matching_substring not in substring_counts):
substring_counts[matching_substring]=1
else:
substring_counts[matching_substring] =1
return substring_counts
# def string_index2(a,b,**ka):
# U,T,N,F=py.importUTNF()
def string_index(a,b=None,line_max=122,escape_eol=('\r','\n'),p=0):
U,T,N,F=py.importUTNF()
r=[[],[],[],[]] #十位 个位 a b
if b:mb=py.len(b)
else:mb=0
w10=0
for n,c in py.enumerate(a):
if (n 1)%line_max==0:
r
# r[2].append('\n'*4)
if escape_eol and c in escape_eol:
c=py.repr(c)[1:-1]
w=T.wcswidth(c)
else:
w=T.wcswidth(c)
w10 =w
r[1].append(T._09[n] ' '*(w-1))
if n==9:
s10=py.str(n//10)
r[0].append(s10 ' '*(w10-py.len(s10)))
w10=0
r[2].append(c)
if n<mb:
r[3].append(b[n])
r= '\n'.join([''.join(row) for row in r])
if p:U.pln(r)
else:return r
enu=enumerate=sindex=str_index=string_index
def similarity_difflib(a,b,isjunk_function=None):
''' '''
import difflib
seq = difflib.SequenceMatcher(isjunk=isjunk_function, a=a,b=b)
ratio = seq.ratio()
return ratio
def char_to_unicode_literal_repr(a,):
repr=a.encode("unicode_escape").decode('ascii')
# if StrRepr:
U,T,N,F=py.importUTNF()
return U.StrRepr(a,repr=repr)
# else:
# return repr
unicode_literal=to_unicode_literal=char_to_unicode_literal_repr
def text_to_varname(a):
''' '''
T
RE_VAR
return
to_varname=text_to_varname
def html_table_to_list(html_or_url,**ka):
'''
pandas.read_html first argument "io" : str, path object or file-like object
A URL, a file-like object, or a raw string containing HTML. Note that
lxml only accepts the http, ftp and file url protocols. If you have a
URL that starts with ``'https'`` you might try removing the ``'s'``.
'''
U,T,N,F=py.importUTNF()
if html_or_url.startswith('https://'):
html_or_url=N.HTTP.get(html_or_url)
import pandas
return pandas.read_html(html_or_url) # return list of tables
def git_convert_ssh(a):
''' '''
U,T,N,F=py.importUTNF()
u=T.regex_match_all(a,T.RE_GIT)[0]
us=u.split('/')
user,repo=us[-2],us[-1]
return '[email protected]:' user '/' repo
git=get_git_ssh=git_convert_ssh
def format_list(a,):
U,T,N,F=py.importUTNF()
r=[]
row_lens=U.len(*a)
maxs=[0]* py.max(row_lens)
return
def format_dict(d,):
U,T,N,F=py.importUTNF()
r={}
max_k,max_v=0,0
id0=0
id_1=0
def fk(a,*aa,**ka):
nonlocal max_k
# py.pdb()()
# U.get_or_set('fk',[]).append([a,py.id(a)])
r=T.padding(py.repr(a._qgb_obj),size=max_k)
if py.id(a._qgb_obj)==id0:
r="\n" r
return r
def fv(a):
nonlocal max_v
# U.get_or_set('fv',[]).append([a,py.id(a._qgb_obj)])
r=T.padding(py.repr(a._qgb_obj),size=max_v)
if py.id(a._qgb_obj)==id_1:
r=r ",\n\n" #TODO '一个\n 在IPython 中显示不出来。'
return r
for n,(k,v) in py.enumerate(d.items()):
s=py.repr(k)
nk=T.wcswidth(s)
if nk>max_k:
max_k=nk
sv=py.repr(v)
nv=T.wcswidth(sv)
if nv>max_v:
max_v=nv
if n==0:
id0=py.id(k)
# print('id0:',id0)
r[U.object_custom_repr(k,repr=fk)]=U.object_custom_repr(v,repr=fv)
else:#只有break后才不执行else
id_1=py.id(v)
# print(n,k,v,id_1)
# r[U.StrRepr(k,repr=s)]=U.StrRepr(v,repr=T.padding(1,size=3))
return r
dict_format=format_dict
def parse_cookie_str_to_dict(s):
T=py.importT()
dc={}
for n,l in py.enumerate(s.split(';')):
l=l.strip()
name=T.sub(l,'','=')
v=l[len(name) 1:]
if name in dc:raise py.Exception('cookie name conflict?',name)
dc[name]=v
#print(l)
# print(n,name,v)
#break
return dc
c2d=parse_cookie=parse_cookie_str=parse_cookie_to_dict=parse_cookie_str_to_dict
def splitlines(*a):
r=[]
for s in a:
r.extend(s.splitlines())
return r
def split_to_2d_list(text,col=re.compile('\s '),row='\n',strip=True,skip_empty_line=True,StrRepr=False):
'''
numpy.loadtxt("myfile.txt")[:, 1]
fname : file, str, or pathlib.Path
File, filename, or generator to read. If the filename extension is
``.gz`` or ``.bz2``, the file is first decompressed. Note that
generators should return byte strings for Python 3k.
'1\r\n2\r\n4'.splitlines()
['1', '2', '4']
'1\n2\r\n4'.splitlines()
['1', '2', '4']
'''
U=py.importU()
if py.islist(text):
rs=text
elif row in ['\n','\r\n']:
rs=text.splitlines()
else:
rs=text.split(row)
r=[]
for i,v in py.enumerate(rs):
if strip:v=v.strip()
if skip_empty_line and not v:continue
cs=re.split(col,v)
if StrRepr:
StrRepr_ka={}
if py.isint(StrRepr) and StrRepr>1:
StrRepr_ka['size']=StrRepr
row=[U.StrRepr(i,**StrRepr_ka) for i in cs]
else:
row=cs
r.append(row)
return r
# import numpy as np
# np.loadtxt("myfile.txt")[:, 1]
# return [ ]
get_2d_list=split2d=split2dlist=split_to_2d_list
def is_contains(text,target):
try:
return target in text
except Exception as e:
return py.No(e)
is_include=include=contains=is_contains
def LF_to_CRLF(text):
if py.istr(text):return regex_replace(text,r'(?<!\r)\n','\r\n')
if py.isbytes(text):return regex_replace(text,br'(?<!\r)\n',b'\r\n')
raise py.ArgumentUnsupported(text)
lf2crlf=LF2CRLF=lf_to_crlf=LF_to_CRLF
def slice(a,start, stop=None, step=1):
''' not only for str '''
if py.isinstance(start,py.slice):
if stop==None and step==1:
start,stop,step=start.start,start.stop,start.step
else:
raise py.ArgumentError('conflict',start,stop,step)
if not py.isint(start):
len=py.len(start)
if len==1:start=start[0]
if len==2 and stop==None:start,stop=start
if len==2 and stop==None and step==1:
start,stop,step=start
try:
return a[start:stop:step]
except Exception as e:
return py.No(e)
get=char_at=charAt=get_char_at=slice
def search_return_position(text,*targets,case_sensitive=True,a=0,b=0,c=0,default_c_size=100,return_target=False,return_dict=False,c_StrRepr=True,index=False,merge_sub=False,**ka):
U=py.importU()
a=U.get_duplicated_kargs(ka,'A',default=a)
b=U.get_duplicated_kargs(ka,'B',default=b)
c=U.get_duplicated_kargs(ka,'C',default=c)
return_target=U.get_duplicated_kargs(ka,'return_target','return_t','t','target',default=return_target)
c_StrRepr=U.get_duplicated_kargs(ka,'c_StrRepr','crepr','cstrrepr',default=c_StrRepr)
case_sensitive=U.get_duplicated_kargs(ka,'cs','case','upper','caseSensitive',default=case_sensitive)
return_dict=U.get_duplicated_kargs(ka,'d','return_dict','rd','dict',default=return_dict)
index=U.get_duplicated_kargs(ka,'index','i','n',default=index)
r=[]
d={}
def _append(t,i,sub=''):
if return_dict:
if sub:
U.dict_add_value_list(d,t,(i,sub))
else :U.dict_add_value_list(d,t,i)
else:
row=[i]
if sub:
row.append( sub)
if return_target:
row.insert(0,t)
if index:
row.insert(0,py.len(r))
r.append(row)
len_text_digits=py.len(str(py.len(text))) #不是digitals
c_isint=py.isint(c)
c_len_2= U.len(c)==2
for t in py.set(targets):
i=0
# re.finditer(re.escape)
while True:
i=text.find(t,i)
if i==-1:break
else:
if a or b or c:
c0=py.max(i-a,0)
c1=i py.len(t) b
if c:
if c_isint:
c0=py.max(i-c,0)
c1=i py.len(t) c
elif c_len_2:
c0=text.rfind(c[0],0,i)
c1=text.find(c[1],i)
if c0==-1 or c0-i>default_c_size:c0=i-(default_c_size//2)
if c1==-1 or i-c1>default_c_size:c1=i-(default_c_size//2)
c0 =1
else:
raise py.ArgumentUnsupported(c)
if c_StrRepr:
_append( t,U.IntRepr(i,size=len_text_digits 1),U.StrRepr(text[c0:c1],size=default_c_size) )
else:
_append( t,i,text[c0:c1] )
else:
_append(t,i,)
i =1 # 不然 死循环
if merge_sub and c_len_2 and r:
dt={}
for row in r:
head=row[:-1]
if py.len(head)==1:head=head[0]
U.dict_add_value_list(dt,row[-1],head)
r=py.list(dt.items())
if r:return r
if d:return d
return py.No('Not found',targets,'in text',py.len(text))
find=find_n=search=search_return_position
def regex_encode(a):
return re.escape(a)
re_escape=regex_escape=regex_encode
def chr_string(chars,alphanumeric=alphanumeric_,quote=quote,chr_func=lambda c:'chr(%s)'%py.ord(c) ,):
s=''
last='' # alphan:a oherchar:c
for c in chars:
if c in alphanumeric:
if not last:
c=quote c
if last=='c':
c=' ' quote c
last='a'
else:
c=chr_func(c)
if not last:pass
if last=='a':
c=quote ' ' c
if last=='c':
c=' ' c
last='c'
s =c
if last=='a':s =quote
U=py.importU()
return U.StrRepr(s)
get_chr_str=make_chr_str=chr_s=chr_str=chr_string
def wc_ljust(text, length, padding=' '):
return text padding * py.max(0, (length - wcswidth(text)))
def wc_rjust(text, length, padding=' '):
'''rjust() 返回一个原字符串右对齐, 在左边填充
'''
# from wcwidth import wcswidth
return padding * py.max(0, (length - wcswidth(text))) text
def wc_cut(s,size):
from wcwidth import wcwidth
width = 0
for n,c in py.enumerate(s):
wcw = wcwidth(c)
if width>=size:
break
if wcw < 0:
width = 0
else:
width = wcw
return s[:n]
def wcswidth(pwcs, n=None):
"""
Given a unicode string, return its printable length on a terminal.
Return the width, in cells, necessary to display the first ``n``
characters of the unicode string ``pwcs``. When ``n`` is None (default),
return the length of the entire string.
if a non-printable character is encountered. 0 width added
#TODO :
T.wcswidth('Stack Overflow на русском')==25 # should be 34
"""
# pylint: disable=C0103
# Invalid argument name "n"
from wcwidth import wcwidth
end = len(pwcs) if n is None else n
idx = py.slice(0, end)
width = 0
for char in pwcs[idx]:
wcw = wcwidth(char)
if wcw < 0:
width = 0
else:
width = wcw
return width #py.No return 0
length_display=char_display_width=display_width=get_display_width=get_str_display_width=wcsize=wcslength=wcswidth
def get_javascript_function(source,function_name):
T=py.importT()
start='async function {}('.format(function_name)
end='}}//end {}'.format(function_name)
#format string '}}'表示一个 },否则 ValueError: Single '}' encountered in format string
r=T.sub(source,start,end)
if not r:
start='function {}('.format(function_name)
r=T.sub(source,start,end)
if not r:
return py.No('not found function {} in js source'.format(function_name),source,start,end)
return start r end
return start r end
getjsf=get_js_func=get_js_function=get_javascript_function
def lxml_etree_to_str(e):
from lxml import etree
h= etree.tostring(e, pretty_print=True).decode()
if '&#' in h:
h=html_decode(h)
return h
x2s=xpath2str=xpath_to_str=xpath_str=xpath_element_to_str=element_to_str=etree_tostring=lxml_to_str=etree_to_str=etree_tostring=lxml_etree_to_str
def xpath(*a,**ka):
''' xpath(astr<optional > ,xpath,file=''<only_optional_ka> ):
'''
from lxml import etree
U=py.importU()
sa_err='ArgumentError: You must provide (either astr or file<only_optional_ka>) and xpath , '
# print(len(a))
if len(a)>2:
return py.No(sa_err 'but got len(a)==%s'% len(a),a,ka)
astr=U.get_duplicated_kargs(ka,'a','ast','astr','s','st','t','text','txt','h','html')
file=U.get_duplicated_kargs(ka,'file','f','FILE','fileName','filename')#last
xpath=U.get_duplicated_kargs(ka,'xpath','x','XPath','xp')
if not xpath:
if len(a) == 1:
if not astr and not file:
return py.No(sa_err 'but only got 1 argument',a)
xpath=a[0]
elif len(a)==2:
if astr:return py.No(sa_err 'but got duplicated [astr]')
astr =a[0]
xpath=a[1]
if file:
if astr or len(a)!=1:
return py.No(sa_err 'not both. len(a)==%s>1'%len(a))
F=py.importF()
file=F.auto_path(file)
e= etree.parse(file, etree.HTMLParser())
else:
e= etree.fromstring(astr, etree.HTMLParser())
return e.xpath(xpath)
def word_wrap(s,width=46,eol=py.No('auto'),**ka):
'''textwrap.wrap(text, width=70, **kwargs)
47: zhuanlan code max len
'''
U=py.importU()
replace_whitespace=U.get_duplicated_kargs(ka,'replace_whitespace','remove_old_eol','del_eol','del_old')
import textwrap
if not eol:
if '\r\n' in s:
eol='\r\n'
else:
eol='\n'
return eol.join(
textwrap.wrap(s, width=width, replace_whitespace=replace_whitespace)
)
break_line=word_wrap
def is_valid_idcard(idcard):
import re
IDCARD_REGEX = '[1-9][0-9]{14}([0-9]{2}[0-9X])?'
if isinstance(idcard, int):
idcard = str(idcard)
if not re.match(IDCARD_REGEX, idcard):
return py.No('IDCARD_REGEX not match',idcard)
items = [int(item) for item in idcard[:-1]]
## 加权因子表
factors = (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2)
## 计算17位数字各位数字与对应的加权因子的乘积
copulas = sum([a * b for a, b in zip(factors, items)])
## 校验码表
ckcodes = ('1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2')
return ckcodes[copulas % 11].upper() == idcard[-1].upper()
sfz=isfz=is_sfz =is_valid_idcard
def columnize(iterable,width=120,**ka):
''' 144 break line in default Win R Cmd window
'''
# from IPython.utils.text import columnize as _columnize
if not py.iterable(iterable):return py.repr(iterable)
U,T,N,F=py.importUTNF()
width=U.get_duplicated_kargs(ka,'size','width','row_width',default=width)
import IPython.utils.text
#TODO dict columnize
# { k1:v
# k2:[small list]
# k3:[long,list,
# auto ident
# and columnize]
# k4:and recursively
# }
if py.isdict(iterable):
return pformat( iterable )
# return pformat( {k:pformat(v) for k,v in iterable.items() } )
r= IPython.utils.text.columnize([pformat(i) for i in iterable],
row_first=True, separator=' , ', displaywidth=width)
return r
col=column=columnize
def justify(s,size=0,char=' ',method=py.No('try use wc_ljust'),cut=False):#'ljust'
''' ljust() 方法返回一个原字符串左对齐,并使用空格填充右边至指定长度的新字符串。
#当提供size 参数时,小心 ModuleNotFoundError: No module named 'wcwidth' # 已经fix部分情况
rpcServer [U.StrRepr(T.az,size=26)]没有错误详情, repr(U.StrRepr(T.az,size=26)) 就有出错详情
'''
s= string(s)
if size<1:
return s
# raise py.ArgumentError('size must > 0',size)
if not method:
try:
from wcwidth import wcwidth
method=wc_ljust
except Exception as e:
method='ljust'
if py.istr(method):
if cut and len(s)>=size:
return s[:size]
return py.getattr(s,method)(size,char) #
if py.callable(method):
if cut and wcswidth(s)>=size:
return wc_cut(s,size)
return method(s,size,char) #TODO 统一参数
raise NotImplementedError('method must str.funcName or callable')
padding=justfy=justify
def encode(s,encoding):
'''
codecs.encode(obj, encoding='utf-8', errors='strict')
'''
def return_error(e):
U,T,N,F=py.importUTNF()
return U.StrRepr('')
return py.No(e)
try:
return s.encode(encoding)
except LookupError:
import codecs
try:
return codecs.encode(s,encoding=encoding)
except Exception as e:
return return_error(e)
except Exception as e:
return return_error(e)
def diff_bytes(b1,b2,p=True):
all_args=py.importU().getArgsDict()
U=py.importU();F=py.importF()
sp=F.mkdir(diff_bytes.__name__)
rf=[]
for k,v in all_args.items():
# print(k,v)
if not py.isbytes(v):continue
f=F.write('{}{}={}'.format(sp,filename_legalized(k),len(v), ) ,v)
rf.append(f)
if py.isbytes(b1):b1=b1.splitlines()
if py.isbytes(b2):b2=b2.splitlines()
import difflib
context = difflib.context_diff
r=difflib.diff_bytes(context, b1 ,b2 )
r=b''.join(r)
if p:
print(r)
else:
rf.insert(0,' '*33)
rf.insert(0,r)
return rf
diffb=diffBytes=diff_bytes
def diff_chars(expected, actual,p=True,enumerate=True,eol=True,**ka):
import difflib
U,T,N,F=py.importUTNF()
enumerate=U.get_duplicated_kargs(ka,'n','index',default=enumerate)
def tolist(a):
r=[]
if enumerate:
for i,c in py.enumerate(a):
if eol:
r.append('{}:{}\n'.format(i,c))
else:
r.append('{}:{}'.format(i,c))
else:
if eol:
r=[c '\n' for c in a]
else:
r=py.list(a)
return r
expected=tolist(expected)
actual=tolist(actual)
# diff=difflib.unified_diff(enumerate(expected), enumerate(actual))
diff=difflib.unified_diff(expected, actual)
r=''.join(diff)
if p:
print(r,'\n diff_len:%s'%len(r))
return U.StrRepr(r,repr='#T.diff(p=1) result,len:%s'%py.len(r))
else:
return r
diffc=diffChar=diffChars=diff_char=diff_chars
def diff(expected, actual,p=True,pformat=False):
"""https://docs.python.org/zh-cn/3/library/difflib.html
Compare two sequences of lines; generate the delta as a unified diff.
Helper function. Returns a string containing the unified diff of two multiline strings.
s.splitlines(keepends=False)
"""
import difflib
U,T,N,F=py.importUTNF()
if pformat:
pformat=T.pformat
try:
pformat=py.from_qgb_import('ipy').pformat
except:pass
if not py.istr(expected):
expected=pformat(expected)
if not py.istr(actual):
actual=pformat(actual)
expected=expected.splitlines(True)
actual=actual.splitlines(True)
diff=difflib.unified_diff(expected, actual)
r=''.join(diff)
if p:
print(r,'\n diff_len:%s'%len(r))
return U.StrRepr(r,repr='#T.diff(p=1) result,len:%s'%py.len(r))
else:
return r
def join_recursively(s,iter,prepend_layer=False,append_layer=False,format_layer=False,_layer=0):
if py.istr(iter):
return iter
else:
si=py.str(_layer)
if prepend_layer:
return s.join([recursive_join(si s,i,_layer=_layer 1,
prepend_layer=True,append_layer=append_layer,format_layer=format_layer
) for i in iter])
if append_layer:
return s.join([recursive_join(s si,i,_layer=_layer 1,
prepend_layer=prepend_layer,append_layer=True,format_layer=format_layer
) for i in iter])
if format_layer:
return s.join([recursive_join(s.format(_layer),i,_layer=_layer 1,
prepend_layer=prepend_layer,append_layer=append_layer,format_layer=True
) for i in iter])
return s.join([recursive_join(s.format(_layer),i,_layer=_layer 1, ) for i in iter])
recursiveJoin=recursive_join=join_recursively
def join_eol(*iterable,separator=EOL,**ka):
r= join(*iterable,separator=separator,**ka)
U=py.importU()
return U.StrRepr(r)
eol_join=join_eol
def join(*iterable,separator=',',**ka):#separator=','
'''T.join( ###<py.No )==''
In [1612]: T.join(1)