2025-12-29_tk_calculator_app_extra.html


001| #:name::Tk Calculator App Extra
002| #:link::https://thehardcorecoder.com/2025/12/29/tk-calculator-app-extra/
003| #:date::2025-12-29
004| #:code::
005| class AlphaMap (dict):
006|     """Transation filter."""
007| 
008|     def __init__ (self, others=""):
009|         '''New AlphaMap instance.'''
010|         self[ord('.')] = '.'
011|         self[ord('_')] = '_'
012|         self[ord("'")] = ''
013| 
014|         # A-Z and a-z...
015|         for cx in range(26):
016|             self[UCA+cx] = chr(UCA+cx)
017|             self[LCA+cx] = chr(LCA+cx)
018| 
019|         # 0 through 9...
020|         for cx in range(10):
021|             self[DIG0+cx] = chr(DIG0+cx)
022| 
023|         # User-supplied characters...
024|         for ch in others:
025|             cx = ord(ch)
026|             assert 0 <= cx < 256, ValueError(f'Illegal character: "{ch}"')
027|             self[cx] = ch
028| 
029|     def __missing__ (self, cx):
030|         """All other characters map to spaces."""
031|         return " "
032| 
033| #:code::
034| from examples import AlphaMap
035| 
036| Text = """\
036| They're $500/12, a #1 price. (10.4% off!)
036| Okay -- it's not without its problems.
036| And: We're glad they were there.
036| """

037| 
038| if __name__ == '__main__':
039|     print(Text)
040|     print()
041| 
042|     textfilter = AlphaMap('#$')
043|     cleantext = Text.translate(textfilter)
044|     print(cleantext)
045|     print()
046| 
047| #:code::
048| class WordCounter:
049|     '''Word-Counter "Calculator".
049| 
049| A basic word-counter to replace the Calculator class.
049| This class replicates the attributes and methods of
049| the Calculator class but just counts words.
049| 
049| Attributes:
049|     tokens              list of words to count
049|     variables           unused but expected
049|     constants           unused but expected
049|     results             output string
049| 
049| Methods:
049|     reset               reset calculator
049|     execute             execute tokens
049| 
049| Class Methods:
049|     opnames             returns empty list
049|     parse_text          given text, return list of words
049| 
049| '''

050|     def __init__ (self, **kwargs):
051|         '''New instance.'''
052|         self.tokens    = []
053|         self.variables = {}
054|         self.constants = {}
055|         self.results = ['']
056| 
057|     def __repr__ (self):
058|         '''Debug string.'''
059|         return f'<{typename(self)} @{id(self):012x}>'
060| 
061|     def __str__ (self):
062|         '''String version.'''
063|         return ' '.join(self.tokens)
064| 
065|     def reset (self):
066|         '''Reset.'''
067|         self.results = ['']
068| 
069|     def execute (self, words=''):
070|         '''Count the list of words.'''
071|         self.tokens = words
072|         self.unique = list(sorted(set(words)))
073|         self.nw = len(self.tokens)
074|         self.nu = len(self.unique)
075|         self.nc = sum(len(word) for word in self.tokens)
076|         text = f'{self.nw} words ({self.nu} unique), {self.nc} chars'
077|         self.results = [text]
078|         return text
079| 
080|     @classmethod
081|     def parse_text (cls, text):
082|         '''Break text into words. Remove all punctuation.'''
083|         txt = text.translate(AlphaMap())
084|         txt = txt.replace('. ', ' ')
085|         if txt.endswith('.'): txt = txt[:-1]
086|         txt = txt.lower()
087|         return txt.split()
088| 
089|     @classmethod
090|     def opnames (cls):
091|         '''No operators but an expected method.'''
092|         return []
093| 
094| #:code::
095| from examples import WordCounter
096| 
097| Text = """\
097| They're $500/12, a #1 price. (10.4% off!)
097| Okay -- it's not without its problems.
097| And: We're glad they were there.
097| """

098| 
099| if __name__ == '__main__':
100|     print()
101|     wc = WordCounter()
102| 
103|     # Break text into words...
104|     words = wc.parse_text(Text)
105| 
106|     # Count the words...
107|     result = wc.execute(words)
108| 
109|     print(result)
110|     print()
111|     print(wc.tokens)
112|     print()
113|     print(wc.unique)
114|     print()
115| 
116| #:code::
117| from examples import WordCounter
118| 
119| Source = '''\
119| Marley was dead: to begin with. There is no doubt
119| whatever about that. The register of his burial was
119| signed by the clergyman, the clerk, the undertaker,
119| and the chief mourner. Scrooge signed it: and
119| Scrooge's name was good upon 'Change, for anything
119| he chose to put his hand to. Old Marley was as dead
119| as a door-nail.
119| 
119| Mind! I don't mean to say that I know, of my own
119| knowledge, what there is particularly dead about a
119| door-nail. I might have been inclined, myself, to
119| regard a coffin-nail as the deadest piece of
119| ironmongery in the trade. But the wisdom of our
119| ancestors is in the simile; and my unhallowed hands
119| shall not disturb it, or the Country's done for. You
119| will therefore permit me to repeat, emphatically,
119| that Marley was as dead as a door-nail.
119| '''

120| 
121| if __name__ == '__main__':
122|     print()
123|     wc = WordCounter()
124| 
125|     # Break text into words...
126|     words = wc.parse_text(Source)
127| 
128|     # Count the words...
129|     result = wc.execute(words)
130| 
131|     print(result)
132|     print()
133|     print(wc.tokens)
134|     print()
135|     print(wc.unique)
136|     print()
137| 
138| #:code::
139| class Application:
140|     """Tk Calculator Application class."""
141| 
142|     def __init__ (self, file='', mode='calc'):
143|         '''New Application instance.'''
144|         self.filename = file
145|         self.mode = mode
146|         self.dirty = False
147|         self.nofile = True
148| 
149|         # Load configuration...
150|         self.config = Configuration()
151| 
152|         # Does the "calculation"...
153|         if self.mode == 'wc':
154|             self.calc = WordCounter()
155|         else:
156|             self.calc = Calculator()
157| 
158|         # Build the window...
159|         self._create_widgets()
160|         self._create_menubar()
161|         # Show ourselves...
162|         self.root.deiconify()
163|         # Load'm if ya got'm...
164|         if self.filename:
165|             self.open_source_file()
166|         # Set focus...
167|         self.update_title()
168|         self.update_status(f'Mode: {self.mode}', '#7fffaf')
169|         self.source.focus()
170| 
171|     ...
172|     ...
173|     ...
174| 
175| #:code::
176| from calc_wdw import Application
177| 
178| if __name__ == '__main__':
179|     print()
180|     try:
181|         app = Application(mode='wc')
182|         app.root.mainloop()
183| 
184|     except Exception as e:
185|         print(f'Oops! {e}')
186| 
187|     else:
188|         print('Success!')
189| 
190|     finally:
191|         print('Done.')
192| 
193|     print()
194| 
195| #:code::
196| from sys import argv
197| from calc_wdw import Application
198| 
199| if __name__ == '__main__':
200|     print()
201|     mode = argv[1] if 1 < len(argv) else 'calc'
202| 
203|     try:
204|         app = Application(mode=mode)
205|         app.root.mainloop()
206| 
207|     except Exception as e:
208|         print(f'Oops! {e}')
209| 
210|     else:
211|         print('Success!')
212| 
213|     finally:
214|         print('Done.')
215| 
216|     print()
217| 
218| #:end:code::
219|