Python - Replace x lines above and below the searched text

Asked

Viewed 30 times

0

Good,

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

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 blax search he removes the 3 previous lines and the 2 following lines, placing in the same place Linha10 blaaaaaa

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

Does anyone have any idea?

Down with 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()

1 answer

0

The tricky thing is to try to do this using 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.