Python - Replace x lines above and below searched text

0

Good,

I needed to do something that in a document filled out for example like:

linha1 bla bla
linha2 bla bla
linha3 bla bla
linha4 bla bla
linha5 bla bla
linha6 bla blax
linha7 bla bla
linha8 bla bla
linha9 bla bla

When doing a search for blax it removes the previous 3 lines and the following 2 lines, placing in the same place Line 10 blaaaaaa

I already have the find working, I do not know how to implement this rule.

Does anyone have an idea?

Below my Find:

def find():
    textarea.tag_remove('found', '1.0', END)
    s = edit.get()
    if s:
        idx = '1.0'
        while 1:
            idx = textarea.search(s, idx, nocase=1, stopindex=END)
            if not idx: break
            lastidx = '%s+%dc' % (idx, len(s))
            textarea.tag_add('found', idx, lastidx)
            idx = lastidx
        textarea.tag_config('found', foreground='red')
    edit.focus_set()
    
asked by anonymous 19.07.2018 / 16:37

1 answer

0

The tricky thing is trying to do this using the tkinter functions that are horrible. If possible extract the text and use python functions - for example regex:

result = re.sub(r'(?:^.+?$\n){3}^.*blax.*$\n(?:^.+?$\n){2}', 
    'Linha10 blaaaaaaa\n', texto, flags=re.MULTILINE)
    
19.07.2018 / 20:59