0

Disclosure: Code not my own just edited from internet and added Regex function.

I want to find numbers in text and replace it with 'number' tag using Regex and the following code does it. I use tkinter to get text from user.

from tkinter import *
root=Tk()
def Reg_ex():
    inputValue=textBox.get("1.0","end-1c")
    A = re.sub("\d+", '<number>',inputValue)
    print(A)
textBox=Text(root, height=40, width=50)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Reg_number", 
                    command= Reg_ex)
buttonCommit.pack()
mainloop()

Obstacle: How to write the print output back into the text box for user to see.

Currently it prints in terminal but I want the output returned to text area for user to see it with original text replaced with reg_ex processed text.

Please Help!

1
  • I suggest you to use another Text. first half for your input text and second half for your output text. Then you can use text.insert("END", value) to insert your input text into output one as your required format Commented Oct 20, 2020 at 4:13

1 Answer 1

1

You could use the replace method of the Text widget.

import tkinter as tk, re

root = tk.Tk() 

textbox = tk.Text(root, height=40, width=50)
textbox.pack()

def replace():
    textbox.replace('1.0', 'end', re.sub("\d+", '<number>', textbox.get('1.0', 'end')))
    
tk.Button(root, width=10, text="replace #'s", command=replace).pack()

root.mainloop()

However, I would argue that it is more useful to do it this way. This version makes replace more dynamic and robust, allowing you to reuse it and externally control it's behavior.

import tkinter as tk, re

root = tk.Tk() 

textbox = tk.Text(root, height=40, width=50)
textbox.pack()

def replace(pattern, repl, count=0, flags=0, rng=('1.0', 'end')):
    textbox.replace(*rng, re.sub(pattern, repl, textbox.get(*rng), count, flags))
    
tk.Button(root, width=10, text="replace #'s", command=lambda: replace('\d+', '<number>')).pack()

root.mainloop()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.