Hi all,

Does anyone know how to search for a string or substring within a list. I have

def searchfilt(self):
        f = open("timeline1.csv", "r") 
        reader = csv.reader(f) 
        
        text = enterbox(msg='Please choose a highlighter search term', title='Highlighter ', default='', strip=True)
        lines = []
        i = -1
        self.listbox2.delete(0, tk.END)
        for i, line in enumerate(reader):
            for words in line:
                if text == words:
                    self.listbox2.itemconfig(i, bg='red', fg='white')
                    self.listbox2.insert(tk.END, line)
                else:
                    self.listbox2.insert(tk.END, line)

This reads in every line from a csv file and checks if a string is in the line. the line is

"1280320019","u'Search Appointments at DkIT'","u'https://recruit.ancheim.ie/dkit/rec/erq_search_package.search_form?p_company=1&p_internal_external=E&p_display_in_irish=N'","Firefox History","Normal Time"

I need to for instance be able to search for ie and if its found highlight it. Im using Tkinter listbox to output the data. This has been wrecking my head.

Thanks to anyone that helps :)

This should give you some insight!

import csv

for row in csv.reader(open('timeline1.csv', 'r')):
    match = None
    for item in row:
        if item.find('.ie/') != -1:
            match = True
    if match:
        print 'Highlighted ->>', row
    else:
        print row

I'm not a tk programmer, but:

def searchfilt(self):
    f = open("timeline1.csv", "r") 
    reader = csv.reader(f) 
    text = enterbox(msg='Please choose a highlighter search term', title='Highlighter ', default='', strip=True)
    lines = []
    i = -1
    self.listbox2.delete(0, tk.END)
    for i, line in enumerate(reader):
        for words in line:
            if words.find(text) != -1:
                self.listbox2.itemconfig(i, bg='red', fg='white')
        self.listbox2.insert(tk.END, line)

Edited 6 Years Ago by Beat_Slayer: n/a

Maybe this consolised piece of code can help something:

def searchfilt():
        text = raw_input('Please choose a highlighter search term:\n')
        for i, line in enumerate(["1280320019","u'Search Appointments at DkIT'",
                                  "u'https://recruit.ancheim.ie/dkit/rec/erq_search_package.search_form?p_company=1&p_internal_external=E&p_display_in_irish=N'",
                                  "Firefox History","Normal Time"]):
            if text in line:
                a,b,c = list(line.partition(text))
                print(''.join((a,'<strong>',b,'</strong>',c))) ## c can have second hit
            else:
                print line

searchfilt()

Edited 6 Years Ago by pyTony: n/a

Cheers for the help.. could I ask you a question. If I wanted to alter your code to read in a file containing multiples of those strings and then check if the string occurs in each line of the list and print out to a text file is that possible. I have tried but am having problems

#!/usr/bin/env python

import csv

def searchfilt():
        text = raw_input('Please choose a highlighter search term:\n')
        f = open("timeline1.csv", "r") 
        reader = csv.reader(f)  
        list = []
        
                    
        #print list   
        for i, line in enumerate(reader):
            if text in line:
                a,b,c = list(line.partition(text))
                list.append(''.join((a,'<strong>',b,'</strong>',c))) ## c can have second hit
                print list
            else:
                #print line
                pass
if __name__ == '__main__':
    searchfilt()

You are redefining list to mean empty list and then you are trying to use it as function.

Maybe something like this?

import csv
def searchfilt(csvfile):
        text = raw_input('Please choose a highlighter search term:\n')                   
        return [(lineno+1,''.join((a,'<strong>',b,'</strong>',c)))
               for lineno,line in enumerate(csv.reader(open(csvfile, "r")))
               for word in line
               for a,b,c in (word.partition(text),)
               if text in word]

if __name__ == '__main__':
    for line in searchfilt("timeline1.csv"):
        print '%i:\t%s' % line

Edited 6 Years Ago by pyTony: Line numbers

Cheers, I ended up with this, but it only gives the first occurance in a line

#!/usr/bin/env python

import csv
from Tkinter import *

def searchfilt():
        text = raw_input('Please choose a highlighter search term:\n')
        f = open("timeline1.csv", "r") 
        #reader = csv.reader(f)  
        reader = f.readlines()
        endLine = len(reader)
        f1 = open("search.txt","w+")
        for i in range(0,endLine):
            #for lne in reader[i]:
            line = str(reader[i])
            line = line.replace(']','(')
            line = line.replace('[','(')
            
            if text in line:
                a,b,c = list(line.partition(text))
                f1.write(''.join((a,'<strong>',b,'</strong>',c))) ## c can have second hit
            else:
                f1.write(line)#print line
                pass
       
if __name__ == '__main__':
    searchfilt()

do while partitioning part 20 & 21 to something like:

found = ' '
while found:
     a,found,text = line.partition(text)
     if found: f1.write(''.join((a,'<strong>',b,'</strong>',c)))
     else: f1.write(a)
f1.write('\n')

Your code is wrong though, you should not change the sequence you iterate during the loop. Also otherwise your code is little strange by using replace which I do not understand.

Compare little your program with thread mentioned in my code snippet:
text file based information access by field name and number

Edited 6 Years Ago by pyTony: n/a

I have actually changed it a bit more and it will now output to a Tkinter Textbox and highlight a user specified text. Its pretty good. Hope it helps someone

def searchfilt(self):
        text = enterbox(msg='Please choose a highlighter search term:\n', title='Start Time filter ', default='', strip=True, image=None, root=None)
      
        f = open("timeline1.csv", "r") 
        #reader = csv.reader(f) 
 
        reader = f.readlines()
        endLine = len(reader)
        #f1 = open("timeline1.csv","w+")
        root7 = tk.Tk()
        root7.geometry("1280x500")

        edit = tk.Text(root7, width=800,height=20)
        edit.pack()
        edit.tag_config('high', foreground='black', background='yellow')
        edit.tag_config('low', foreground='black', background='white')
        
        for i in range(0,endLine):
          
            line = str(reader[i])
            line = line.replace(']','(')
            line = line.replace('[','(')
            
            if text in line:
                a,b,c = list(line.partition(text))
                
                edit.insert('insert', a,'low')
                edit.insert('insert',b, 'high')
                edit.insert('insert',c,'low')
                
            else:
              
                edit.insert('end',line, 'low')
                
        root7.mainloop()

Still I do not understand the purpose of lines 21 and 22. Looks that you have learned to use tags. Nice work.

Wouldn't this do the same?

import Tkinter as tk
from easygui import *
def searchfilt():
        root7 = tk.Tk()
        root7.geometry("1000x500")

        edit = tk.Text(root7, width=400,height=20)
        edit.pack()
        edit.tag_config('high', foreground='black', background='yellow')
        edit.tag_config('low', foreground='black', background='white')
        text = enterbox(msg='Please choose a highlighter search term:\n',
                        title='Start Time filter ',
                        strip=True,
                        root=root7)
        
        for line in  open("timeline1.csv"):            
            if text in line:
                for part in zip(line.partition(text),('low','high','low')):
                    edit.insert('insert',*part)               
            else:
                edit.insert('end',line, 'low')
                
        root7.mainloop()

searchfilt()

If you want to search for all hit positions from text you can use this function as for loop iterator.

def multis(search,text,start=0):
    while start>-1:
        f=text.find(search,start)
        start=f
        if start>-1:
            yield f
            start+=1
This article has been dead for over six months. Start a new discussion instead.