나는 어제이 질문을했으나 여전히 그것에 붙어 있습니다. 현재 파일을 올바르게 읽는 함수를 작성했지만 몇 가지 문제가 있습니다.CSV 파일을 사전으로 변환
내가 겪고있는 주된 문제는 필자가 파일의 첫 번째 줄을 건너 뛰고 사전으로 반환할지 잘 모르겠다는 것입니다. 내가 지금 무엇을
다음sample_dict = {
"Pablo Picasso": [("Guernica", 1937, 349.0, 776.0, "oil paint", "Spain")],
"Leonardo da Vinci": [("Mona Lisa", 1503, 76.8, 53.0, "oil paint", "France"),
("Portrait of Isabella d'Este", 1499, 63.0, 46.0, "chalk", "France"),
("The Last Supper", 1495, 460.0, 880.0, "tempera", "Italy")],
"Vincent van Gogh": [("Cafe Terrace at Night", 1888, 81.0, 65.5, "oil paint", "Netherlands"),
("Self-Portrait with Bandaged Ear",1889, 51.0, 45.0, "oil paint", "USA")]
}
것 :
나는 위와 같은 파일을 읽고 다음과 같습니다 사전으로 변환 할 필요가"Artist","Title","Year","Total Height","Total Width","Media","Country"
"Pablo Picasso","Guernica","1937","349.0","776.0","oil paint","Spain"
"Vincent van Gogh","Cafe Terrace at Night","1888","81.0","65.5","oil paint","Netherlands"
"Leonardo da Vinci","Mona Lisa","1503","76.8","53.0","oil paint","France"
"Vincent van Gogh","Self-Portrait with Bandaged Ear","1889","51.0","45.0","oil paint","USA"
"Leonardo da Vinci","Portrait of Isabella d'Este","1499","63.0","46.0","chalk","France"
"Leonardo da Vinci","The Last Supper","1495","460.0","880.0","tempera","Italy"
: 다음 파일 중 하나의 예입니다 멀리. 현재 코드는 작동하지만 위의 예와 같이 파일을 사전으로 변환하지 않습니다. 어떤 도움 주셔서 감사합니다
def convertLines(lines):
head = lines[0]
del lines[0]
infoDict = {}
for line in lines:
infoDict[line.split(",")[0]] = [tuple(line.split(",")[1:])]
return infoDict
def read_file(filename):
thefile = open(filename, "r")
lines = []
for i in thefile:
lines.append(i)
thefile.close()
mydict = convertLines(read_file(filename))
return lines
내 코드가 약간 변경되면 정확한 결과가 나타나지 않습니까? 아니면 다르게 접근해야합니까? 현재 코드가 전체 파일을 읽는 것으로 나타납니다. 어떤 도움 주셔서 감사합니다
편집 : @Julien 오늘 수정 사항을 작성하기 전까지 재귀 오류가 발생했습니다 (올바르게는 안됨). 그것을 할 필요가있는 경우
현재 함수가 무한 자체를 호출def read_file(filename):
with open(filename, "r") as thefile:
mydict = convertLines(thefile.readlines()))
return mydict
... 그런 다음 convertLines
기능을 수정 :
어떤 결과가 당신에게 불만을 느끼게합니까? 이것은 관련성이있는 정보이므로 친절하게 공유하십시오! – Julien
나는 목록에 추가하는 대신 각 아티스트의 각 결과를 덮어 쓰는 중입니다 ... – Julien
현재 코드에서 실제로 재귀 오류가 발생하지만 기본적으로 키가 아티스트 인 사전을 만들 수 없었습니다. 이름과 값은 그림입니다. 위 예제의 경우 파일에서 이름을 반복 할 수 있고 값은 그림입니다 (피카소 1, 다빈치 3, 반 고흐 2) – n00bprogrammer22