I wrote the script, but didn't advise how to put it in. On the text object itself, right-click, and "Edit Script Events". Then, in the "OnSetText" tab (should be selected at start), enter the script above, and compile (click on the red lightning bolt, or hit F7, or choose "Script>Compile from the menu).
Your script is now applied to run at OnSetText for that text object. You can apply different scripts to objects or scenes, or run them at different times in the sequencer (OnOnline, OnRender, OnPreviewRender, etc...).
#XPression