#python #excel #dictionary #replace #openpyxl
Вопрос:
Я пытаюсь взять данные из столбца 1 в файле XLSX, найти их в XML-файле и заменить их данными из столбца 2 таким образом, чтобы содержимое ячейки слева (столбец 1) было заменено содержимым ячейки справа (столбец 2).
У меня есть следующий код, который работает, но я чувствую, что это плохой способ сделать это, и это можно было бы сделать гораздо проще и эффективнее.
Вот файл xlsx: изображение таблицы xlsx
Вот мой текущий код:
`import openpyxl wb = openpyxl.load_workbook(".\2-column-sample.xlsx") #opening file sheet=wb.active rows = sheet.rows headers = [cell.value for cell in next(rows)] all_rows = [] #creating empty list for row in rows: #parsing column 1 and column 2 toa dictionary data = {} for title, cell in zip(headers, row): data[title] = cell.value all_rows.append(data) #appending dictionary data to a list print(all_rows) #check if the list containing dictionaries displays date as intended #create 2 lists: 1st for terms from column 1, 2nd for terms from column 2 list_1 = [] list_2 = [] for value in all_rows: list_1.append(value['Wrong_terms']) list_2.append(value['Updated_terms']) #assign variables for each interated value from each list n1, n2, n3, n4, n5, n6, n7, n8 = list_1 t1, t2, t3, t4, t5, t6, t7, t8 = list_2 #check if pairs are correctly extracted from one of the dictionaries inside the list print(n1, t1) #replace terms in column 1 that are found in xml file with the terms from column 2 and save updated xml file with open(".\file_to_be_changed.xml", "rt") as fin: with open(".\file_to_be_updated.xml", "wt") as fout: for line in fin: fout.write(line.replace(n1, t1).replace(n2, t2) .replace(n3, t3).replace(n4, t4) .replace(n5, t5).replace(n6, t6) .replace(n7, t7).replace(n8, t8)) `