【发布时间】:2017-03-26 22:58:53
【问题描述】:
我编写了一个当前可以正确读取文件的函数,但存在一些问题。它需要作为字典返回,其中键是艺术家姓名,值是元组列表(对此不确定,但这似乎是它的要求)
我遇到的主要问题是我需要以某种方式跳过文件的第一行,并且我不确定是否将其作为字典返回。以下是其中一个文件的示例:
"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"
所以我需要读取一个输入文件并将其转换成一个如下所示的字典:
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")]
}
我遇到的主要问题是跳过显示“艺术家”、“标题”等的第一行,只返回第一行之后的行。我也不确定我当前的代码是否将其作为字典返回。这是我目前所拥有的
def convertLines(lines):
head = lines[0]
del lines[0]
infoDict = {}
for line in lines: #Going through everything but the first line
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
对我的代码进行一些小的更改会返回正确的结果,还是我需要以不同的方式处理这个问题?看来我当前的代码确实读取了完整的文件,但是如果还没有,我将如何跳过第一行并可能以 dict 表示形式返回?感谢您的帮助
【问题讨论】:
标签: python file python-3.x csv dictionary