vendredi 2 mars 2018

Unexpected Function Behavior In Python

I am working on cleaning up my code into defined functions for repeated tasks. The body of the code works fine when I run each block individually. However, when I define the function as follows, it just jumps to the else condition. How should I write the if and elif statements to the execute properly? Any recommendations how I can make this function more succinct? I'm still a beginner programmer. Thanks!

def clean_up_list_of_dicts(raw_list):
    wanted_keys_fb = ['Title', 'Location', 'Price', 'Description', 'Url']
    wanted_keys = wanted_keys_fb + ['Latitude', 'Longitude'] 

    if 'fb_used_items_raw':
        with open('fb_used_items_filtered.txt', 'w+') as file:
            for item in fb_used_items_raw:
                for k in wanted_keys_fb:
                    lines = item[k].split()
                    split_lines = [line for line in lines if line.strip()]            
                    file.write("{}".format(' '.join(split_lines)) + '\t')
            file.write('\n')

    elif 'lg_used_items_raw':
        with open('lg_used_items_filtered.txt', 'w+') as file:
            for item in lg_used_items_raw:
                for k in wanted_keys:
                    lines = str(item[k]).split()
                    split_lines = [line for line in lines if line.strip()]            
                    file.write("{}".format(' '.join(split_lines)) + '\t')
                file.write('\n')
    else:
        with open('cl_used_items_filtered.txt', 'w+') as file:
            for item in cl_used_items_raw:
                for k in wanted_keys:
                    if k == 'Description':
                        lines = str(''.join(item[k])).split()
                        split_lines = [line.replace('\n', '').strip() for line in lines]
                        split_lines = ' '.join(split_lines)
                        file.write(split_lines + '\t')
                    else:
                        lines = str(item[k]).split()
                        split_lines = [line.replace('\n', '').strip() for line in lines]
                        file.write("{}".format(' '.join(split_lines)) + '\t')
                file.write('\n')

    file.close()


clean_up_list_of_dicts(fb_used_items_raw)
clean_up_list_of_dicts(lg_used_items_raw)
clean_up_list_of_dicts(cl_used_items_raw)

Aucun commentaire:

Enregistrer un commentaire