1

Tengo dos archivos pickle, Airline_XYZ.p:

[{}, {}, {'Gender *': ['Female', 'Male', 'Autre :'], 'Please provide your age in years. *': [], 'Please indicate your country of residence. *': [], 'For respondents from the United States, please provide the ZIP c
ode of your primary residence *': [], 'If you are an Amazon Mturk worker, please provide your ID below. If you are not an Mturk worker, please type NULL *': []}, {}]

y Hotel_Chain_ABC.p:

[{}, {'How can we make your hotel shuttle trip, post COVID-19': ['Private shuttle', 'Shuttle with passenger limits', 'Protective glass arou
nd each seat', "Disposable PPE's onboard", 'Sanitizer onboard', "Driver in full PPE's", 'Other:'], 'How can we make you feel safe in our Hotel/Motel post COVID-19': ['Electronic doors', "Employees in full PPE's",
'Limits on the amount of people in Lobby', 'Protective glass at check-in station', 'A way to enter your room without key cards or keys', 'Have sheets and towels enclosed in individual plastic covering', 'Other:']]

Me gustaría hacer un csv de ellos con las siguientes columnas pickle_file_name, question, answer1, answer2 , answer_3, ... para cada respuestas para una pregunta

Hasta ahora sé cómo extraer la pregunta y las respuestas:

>>> all_questions = pickle.load( open( "Airline_XYZ.p", "rb" ) )
>>> l_question = []
>>> for element in all_questions:
...     for question in element:
...         l_question.append({"question": question, "answer": element[question]})
...

No sé cómo crear los diferentes answer_i columnas, ni cómo insertarlos con el otro en un csv.

1 respuesta 1

1

El principal problema a resolver es que no sabemos el total de columnas hasta no haber iterado sobre todos los archivos. Podemos reolverlo de varias formas, bien iterando dos veces sobre cada uno para obtener el total de columnas o iterando una sola vez pero almacenando el contendido de todos ellos en memoria simultáneamente. La elección dependerá del tamaño de los archivos y de si te importa o no el consumo de RAM.

Para la segunda opción podemos hacer algo como:

import csv
import pickle
import pathlib


all_files = ["Airline_XYZ.p", "Hotel_Chain_ABC.p"]

all_rows = []
for file_strpath in all_files:
    file_path = pathlib.Path(file_strpath)
    with open(file_path, "rb") as file:
        pages = pickle.load(file)    

    for page in pages:
        for question, answers in page.items():
            row = {
                "pickle_file_name": file_path.resolve().stem, 
                "question": question
                }
            for i, answer in enumerate(answers):
                row[f"answer_{i + 1}"] = answer
            all_rows.append(row)

fieldnames = max((row.keys() for row in all_rows), key=len)
with open("result.csv",  "w") as file:
    dict_writer = csv.DictWriter(file, fieldnames)
    dict_writer.writeheader()
    dict_writer.writerows(all_rows)

Genera el CSV:

pickle_file_name,question,answer_1,answer_2,answer_3,answer_4,answer_5,answer_6,answer_7
Airline_XYZ,Gender *,Female,Male,Autre :,,,,
Airline_XYZ,Please provide your age in years. *,,,,,,,
Airline_XYZ,Please indicate your country of residence. *,,,,,,,
Airline_XYZ,"For respondents from the United States, please provide the ZIP code of your primary residence *",,,,,,,
Airline_XYZ,"If you are an Amazon Mturk worker, please provide your ID below. If you are not an Mturk worker, please type NULL *",,,,,,,
Hotel_Chain_ABC,"How can we make your hotel shuttle trip, post COVID-19",Private shuttle,Shuttle with passenger limits,Protective glass around each seat,Disposable PPE's onboard,Sanitizer onboard,Driver in full PPE's,Other:
Hotel_Chain_ABC,How can we make you feel safe in our Hotel/Motel post COVID-19,Electronic doors,Employees in full PPE's,Limits on the amount of people in Lobby,Protective glass at check-in station,A way to enter your room without key cards or keys,Have sheets and towels enclosed in individual plastic covering,Other:

He ignorado los diccionarios vacíos de cada lista, no obstante, si es necesario, se puede escribir una línea vacía en el CSV para representarlos, bastaría un condicional para detectar si el diccionario (page) está vacío antes de iterar.

En la columna pickle_file_name he agregado el nombre de archivo sin la extensión, si se quiere la extensión, solo cambiar:

file_path.resolve().stem

por:

file_path.resolve().name

all_files puede contener rutas relativas o absolutas a los ficheros, es indiferente, por eso hago uso de pathlib.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.