dimanche 26 septembre 2021

A function that replaces and removes elements from a lines within a list

Pretty new to coding, imagine theres something straightforward here im missing. Im trying to manipulate geo-tags for a coding course (eg. (36.22, -115.25); (36.13, -115.16); (36.22, -115.25))- roughly 6 lines with multiple geo-tags per line.

Aim is to create a function that replaces some geo-tag locations (loc_old) with new locations (loc_new) and removes others.

Also trying to remove duplicate geo-tags and arrange in ascending order.

Code currently:



def load_from_file(filename):
    """convert to unicode and return line"""
    lines = []
    with open(filename, encoding="utf-8") as file:
        for line in file: 
            line = line.strip()
            lines.append(line)
    return lines

def multiple_task(filename, loc_old, loc_new, loc_remove):
    """replace old with new and then remove specified locations"""
    line_list = load_from_file(filename) ### Previous function that creates list from tex doc
    loc_old = loc_old.strip()
    loc_new = loc_new.strip()
    loc_remove = loc_remove.strip()
    results = []
    for elements in line_list:
        if elements not in results: ### using **not in** to prevent duplicates being added
            if elements in loc_old:
                results.append(loc_new) ### adding loc_new in place of loc_old
            elif elements not in loc_old:
                results.append(elements)
    for elements in results:
        if elements == loc_remove:
            results.remove(elements) ###removing elements that have the same value as loc_remove
            results.sort() ### sorting in ascending order
    return results

Output

output = multiple_task('original.txt', '(36.13, -115.16)', '(36.16, -115.16)', '(33.34, -111.88)') print(output[3])

(41.5, -81.7); (41.43, -81.51); (41.52, -81.34); (41.4, -81.63); (41.5, -81.71); (41.42, -81.5); (41.52, -81.35); (41.13, -81.55); (41.5, -81.7); (41.52, -81.36); (41.41, -81.35); (41.52, -81.34); (41.52, -81.34)

Currently output is the correct line... but not in ascending order and now duplicates

Aucun commentaire:

Enregistrer un commentaire