Search code examples
pythonarraysfindhighlighting

python choose one object from array


I have a script that is returning the start/end locations of strings in a gtk textview object. I feel like I am doing the same thing over and over. the first search function returns the start,end of each match location. the second I was hoping would search and highlight each object in the textview given by the array. the searchn() I noticed that I can change the array selection and choose the 2nd to last or what ever I choose.

Is there a way to choose one at a time each object that in an array per click so it will highlight the one object in order in the array.

so If I have four words

work work work work

then I can highlight the first one then I click again and it will re-run the function and highlight the 2nd then 3rd and when it is all complete I can just make it go back to the beginning.I was thinking that someting like. for range in len(z): do this but no matter what I do it in a for loop it selects the last one steps on the last. I hope this makes sense.

def search(x):
search_required = False
sbuffer.remove_tag_by_name('found', sbuffer.get_start_iter(), sbuffer.get_end_iter())
    find_text = findentry.get_text()
    if find_text:
  text = sbuffer.get_text(sbuffer.get_start_iter(),sbuffer.get_end_iter()).decode('utf8')
      search_matches = [(match.start(), match.end()) for match in re.finditer(re.escape(find_text), text, re.IGNORECASE)]
      if len(search_matches) < 1000:
    for start,end in search_matches:
      iter1 = sbuffer.get_iter_at_offset(start)
      iter2 = sbuffer.get_iter_at_offset(end)
      sbuffer.select_range(iter1, iter2)
      sbuffer.apply_tag_by_name('found', iter1, iter2)
    textview.scroll_to_mark(sbuffer.get_mark('insert'), 0.25)
    print search_matches
    return search_matches
else:
  search_matches = [ ]    



  def searchn(x):
search(x)
z=search(x)
#def SN(z)
print len(z)
z=z[:1]# need to have this do to 2nd,3rd,4th,5th ect till there are no more matches.
for a,l in z:
  print a,"start of this match"
  print l, "end of this match"
  iter1 = sbuffer.get_iter_at_offset(a)
  iter2 = sbuffer.get_iter_at_offset(l)
  sbuffer.select_range(iter1,iter2)
  print z
return z  

Thank you in advance!


Solution

  • Why don't you use regex to find the instances of the word you are looking for and then once you have all the indexes do your looping.

    Example:

    import re
    sentence = "You are my favorite. Are you my friend? Are you an elephant?"
    items = []
    for item in re.finditer("[Aa]re", sentence, ):
        items.append(item.start())
    

    This should give you the locations that the words are at. Once you have those, you should be able to quickly and easily step through those locations any way you like.