Create recursive Python function with multiple conditions

Viewed 351

Background: I am trying to write a function that parses message data out of a plain text document I've converted from a PDF. I've parsed and cleaned the data up to a convenient point, such that each line of relevant text is recognized and labeled with an appropriate category. The categories are (Author, Sent, Body, Attachments).

The problem: I am trying to write a function that will separate out data into individual messages. For instance, after it process a line (or lines) belonging to each category, it will output a singular message and then repeat the process once it encounters the beginning of the tuple again. In other words, once it reads Author then Sent then Body then Attachments, when it sees Author again, it should know to start a new message.

I've created a variable next_category that determines, as the name implies, the category of the upcoming line. So long as the index of the upcoming category is not 0, the function should operate. When it the next category is 0, it should repeat the operation on the new lines, until it reaches 0 again, and so on.

Finally, there's a condition wherein next_category can equal None in which case the function should exit completely.

The code:

    def message_parse(thread_dict):
        categories = ('Author', 'Sent', 'Body', 'Attachments')
        category = None


        for line in range(len(thread_dict['data'])):
            # determine first word in line
            first_word = thread_dict['data'][line].split(' ')[0]

            try:
                # determine first word in upcoming line
                next_first = first_word = thread_dict['data'][line+1].split(' ')[0]
            except:
                next_first = None

            if next_first in categories:
                next_category = next_first

            if first_word in categories:
                category = first_word


                if category != None:
                    line_data = thread_dict['data'][line]
                    if not 'DRAFT' in line_data:
                        if line_data != 'EXC':
                            line_data = line_data.strip(category).strip(' ')

                        while next_first != None:    
                            if categories.index(next_category) != 0:
                                # do something?

My instinct tells me I need to create a recursive function to accomplish this, but I've hit a wall trying to come up with something. Can anyone point me in the right direction?

Thanks so much.

0 Answers
Related