2025-03-31_simple-python-tricks-15.html
001|
002|
003|
004|
005| from re import compile
006|
007| class Person:
008| '''Trivial Person class but with formatting!'''
009|
010| regx = compile('^(\d+|\*)f(.*)(\d+|\*)l(.*)$')
011|
012|
013|
014|
015|
016|
017|
018|
019|
020| def __init__ (self, fname, lname):
021| self.fname = fname
022| self.lname = lname
023|
024| def __repr__ (self):
025| return f'{self.fname} {self.lname}'
026|
027| def __format__ (self, fstr):
028| '''Format template: <num>f<sep><num>l<end>'''
029| if not fstr:
030| return str(self)
031|
032|
033| mobj = self.regx.match(fstr)
034| if mobj is None:
035|
036| raise ValueError(f'Illegal format spec: "{fstr}"')
037|
038| grps = mobj.groups()
039| if len(grps) != 4:
040|
041| raise ValueError(f'Invalid format spec: "{fstr}"')
042|
043|
044| fnx = len(self.fname) if grps[0]=='*' else int(grps[0])
045| lnx = len(self.lname) if grps[2]=='*' else int(grps[2])
046| sep = grps[1]
047| end = grps[3]
048|
049|
050| return self.fname[:fnx]+sep+self.lname[:lnx]+end
051|
052|
053| from examples import Person
054|
055| tests = [
056| '*f *l',
057| '*f0l',
058| '0f*l',
059| '1f. *l',
060| '1f1l',
061| '1f.1l.',
062| '1f. 1l.',
063| '2f*l:',
064| ]
065|
066| p = Person('John', 'Smith')
067|
068| for ix,f in enumerate(tests):
069| print(f'{ix:d}: f-string = {f:7s} => {p:{f}}')
070|
071|
072| TAB = ord('\t')
073| EOL = ord('\n')
074| SPC = ord(' ')
075|
076| UCA,UCZ = ord('A'),ord('Z')
077| LCA,LCZ = ord('a'),ord('z')
078| DIG0,DIG9 = ord('0'),ord('9')
079|
080|
081| from examples import UCA,UCZ, LCA,LCZ, DIG0,DIG9
082|
083| class Rot13:
084| """Convert text and numbers to ROT13 versions."""
085|
086| def __getitem__ (self, key):
087| """Return ROT13 versions of alnums."""
088| if UCA <= key <= UCZ: return UCA+(((key-UCA)+13)%26)
089| if LCA <= key <= LCZ: return LCA+(((key-LCA)+13)%26)
090| if DIG0 <= key <= DIG9: return DIG0+(((key-DIG0)+5)%10)
091| return key
092|
093| if __name__ == '__main__':
094| txt = 'The quick brown fox jumped over the lazy dog.'
095| num = 'Invoice Number 03483-25481'
096|
097| r13 = Rot13()
098|
099| out1 = txt.translate(r13)
100| out2 = num.translate(r13)
101|
102| print(f'txt = "{txt}"')
103| print(f'txt > "{out1}"')
104| print(f'out > "{out1.translate(r13)}"')
105| print()
106|
107| print(f'num = "{num}"')
108| print(f'num > "{out2}"')
109| print(f'out > "{out2.translate(r13)}"')
110| print()
111|
112|
113| from examples import UCA,UCZ, LCA,LCZ, DIG0,DIG9, SPC
114|
115| class CleanUrl (dict):
116| """Translate for URL: Accept alnums (others to %## hex)."""
117|
118| def __init__ (self):
119| """Initialize instance with special chars."""
120| super().__init__()
121| self[SPC] = '+'
122|
123| def __getitem__ (self, key):
124| """Explicitly pass alnums. Delegate others."""
125| if UCA <= key <= UCZ: return key
126| if LCA <= key <= LCZ: return key
127| if DIG0 <= key <= DIG9: return key
128| return super().__getitem__(key)
129|
130| def __missing__ (self, key):
131| """Convert non-special chars to %## hex."""
132| return '%%%02X' % key
133|
134|
135| class Text2Html (dict):
136| """Convert &, <, >, " to HTML entities."""
137|
138| def __init__ (self):
139| """Initialize instance with special chars."""
140| self[ord('&')] = '&'
141| self[ord('<')] = '<'
142| self[ord('>')] = '>'
143| self[ord('"')] = '"'
144|
145| def __missing__ (self, key):
146| """Allow all other chars."""
147| return key
148|
149|
150| if __name__ == '__main__':
151| url = r'https://foo.bar.com/base/path/sub/path?a = 21&b = <4> & c=zap'
152| htm = r'He said, <em>"Why not?"</em>, & this & that.'
153|
154| txt2url = CleanUrl()
155| txt2htm = Text2Html()
156|
157| print(f'url = "{url}"')
158| print(f'url > "{url.translate(txt2url)}"')
159| print()
160|
161| print(f'htm = "{htm}"')
162| print(f'htm > "{htm.translate(txt2htm)}"')
163| print()
164|
165|
166| class CharStripper:
167| """Strip characters in mask from string."""
168|
169| def __init__ (self, mask):
170| """Initialize with mask chars."""
171| self.m = [ord(char) for char in mask]
172|
173| def __getitem__ (self, key):
174| """Strip chars in mask, allow all others."""
175| return (None if key in self.m else key)
176|
177|
178| class CharFilter (dict):
179| """Filter for characters in mask, otherwise strip."""
180|
181| def __init__ (self, mask):
182| """Initialize self with mask chars."""
183| super().__init__()
184| for char in mask:
185| self[ord(char)] = ord(char)
186|
187| def __missing__ (self, key):
188| """Strip chars not in map."""
189| return None
190|
191|
192| if __name__ == '__main__':
193| txt = 'The quick brown fox jumped over the lazy dog.'
194|
195| cs = CharStripper('aeiou y')
196| cf = CharFilter('aeiouy')
197|
198| print(f'txt = "{txt}"')
199| print(f'txt > "{txt.translate(cs)}"')
200| print(f'txt > "{txt.translate(cf)}"')
201| print()
202|
203|
204| from examples import UCA,UCZ, LCA,LCZ, DIG0,DIG9
205|
206| CMAP = [None for _ in range(32)]+ ['_'] + ['$' for _ in range(15)]+ [DIG0+c for c in range(10)] + ['$' for _ in range(6)]+ ['$'] + [UCA+c for c in range(26)] + ['$' for _ in range(5)]+ ['$'] + [LCA+c for c in range(26)] + ['$' for _ in range(5)]+ ['?']
207|
208| if __name__ == '__main__':
209| txt = 'The quick brown fox jumped over the lazy dog.'
210|
211| print(f'txt = "{txt}"')
212| print(f'txt > "{txt.translate(CMAP)}"')
213| print()
214|
215|
216| UpsideDown = {
217|
218| 33:0x00a1, 38:0x214b, 63:0x00bf,
219|
220|
221| 48:0x0030, 49:0x21c2, 50:0x218a, 51:0x218b, 52:0x07c8,
222| 53:0x100c, 54:0x0039, 55:0x1d613, 56:0x0038, 57:0x0036,
223|
224|
225| 65:0x2c6f, 66:0xa4ed, 67:0x0186, 68:0xa4f7, 69:0x018e,
226| 70:0x2132, 71:0x2141, 72:0x0048, 73:0x0049, 74:0xa4e9,
227| 75:0xa7b0, 76:0xa780, 77:0xa7fd, 78:0x004e, 79:0x004f,
228| 80:0x0500, 81:0xa779, 82:0xa4e4, 83:0x0053, 84:0xa7b1,
229| 85:0x0548, 86:0x0245, 87:0x10935, 88:0x0058, 89:0x2144,
230| 90:0x005a,
231|
232|
233| 97:0x0250, 98:0x0071, 99:0x0254, 100:0x0070, 101:0x01dd,
234| 102:0x025f, 103:0x0253, 104:0x0265, 105:0x1d09, 106:0x017f,
235| 107:0x029e, 108:0xa781, 109:0x026f, 110:0x0075, 111:0x006f,
236| 112:0x0064, 113:0x0062, 114:0x0279, 115:0x0073, 116:0x0287,
237| 117:0x006e, 118:0x028c, 119:0x028d, 120:0x0078, 121:0x028e,
238| 122:0x007a,
239| }
240|
241| if __name__ == '__main__':
242| txt = 'The quick brown fox jumped over the lazy dog.'
243|
244| print(f'txt = "{txt}"')
245| print(f'txt > "{txt.translate(UpsideDown)}"')
246| print()
247|
248|
249|