Search code examples
pythoninputraw-inputfunction

Python Search function in a tab delimited column file


while True:
    try:
        OpenFile=raw_input(str("Please enter a file name: ")) 
        infile=open(OpenFile,"r")
        contents=infile.readlines()
        infile.close()

        user_input = raw_input(str("Enter A=<animal> for animal search or B=<where lives?> for place of living search: \n")) 
        if user_input.startswith("A="):
            def find_animal(user_input,column):
                return next(("\t".join(line) for line in contents
                             if line[column-1]==user_input),None)
            find_animal(user_input[1:]) 
            print str((find_animal(user_input[1:], "WHO?"))) #"Who?" is the name of the first column.

        else:
            print "Unknown option!"


    except IOError:
        print "File with this name does not exist!"

1.Enter the name of an animal.

2.Program searches for the lines that have this particular name in the first column.

3.Program prints lines that have this name in the first column.

My function can't seem to work properly here. Can you please help me find the mistake(s)? Thank you!

EDIT

      def ask_for_filename():
         filename=str(raw_input("Please enter file name: "))
         return filename

      def read_data(filename): 
         contents=open(filename,"r")
         data=contents.read()
         return data

      def  column_matches(line, substring, which_column):  
         for line in data:
             if column_matches(line, substring, 0):
                print line

Solution

  • Big chunks of code are hard to read and debug, try splitting your code into smaller functions, for example like this:

    def ask_for_filename():
        #left as an exercise
        return filename
    
    def read_data(filename):
        #left as an exercise
        return data
    
    def column_matches(line, substring, which_column):
        #left as an exercise
    
    def show_by_name(name, data):
        for line in data:
            if column_matches(line, name, 0):
                print line
    
    def do_search(data):
        propmt = "Enter A=<animal> for animal search or B=<where lives?> for place of living search: \n"
        user_input = raw_input(prompt)
        if user_input.startswith('A='):
            show_by_name(user_input[2:], data)
    
    # main program
    
    filename = ask_for_filename()
    data = read_data(filename)
    while True:
        do_search(data)
    

    Test and debug these functions separately until you're sure they work properly. Then write and test the main program.

    column_matches() is supposed to return true if some column (which_column) in a line is equal to substring. For example, column_matches("foo\tbar\tbaz", "bar", 1) is True. To achieve that

    • split a line by a delimiter - this gives us a list of values
    • get the n-th element of the list
    • compare it with the substing
    • return True if they are equal and False otherwise

    Putting it all together:

    def column_matches(line, substring, which_column):
        delimiter = '\t'
        columns = line.split(delimiter)
        value = columns[which_column]
        if value == substring:
            return True
        else:
            return False
    

    or, in a more concise and "pythonic" form:

    def column_matches(line, substring, which_column):
        return line.split('\t')[which_column] == substring