【发布时间】:2016-11-13 19:12:47
【问题描述】:
学习 python 并且无法理解如何创建此函数来读取文件并将其作为字典返回。我知道我需要打开文件然后使用 .read(),但到目前为止我不确定如何对数据进行排序。由于会有多个“标题”,我试图将大写字母排序在所有小写字母之前。关于如何进行的任何建议?
到目前为止我的代码:
def read_text(textname):
d = {}
with open(textname) as f:
for line in f:
(title, year, height, width, media, country) = line.split() # I need to skip the first line in the file as well which just shows the categories.
文本文件示例:
text0='''"Artist","Title","Year","Total Height","Total
Width","Media","Country"
"Leonardo da Vinci","Mona Lisa","1503","76.8","53.0","oil paint","France"
"Leonardo da Vinci","The Last Supper","1495","460.0","880.0","tempera","Italy"
我想要返回的文件为:
{'Leonardo da Vinci': [("Mona Lisa",1503,76.8,53.0,"oil paint","France"),
('The Last Supper', 1495, 460.0, 880.0, 'tempera', 'Italy')]}
【问题讨论】:
-
@UnholySheep 这是一个 csv 文件
-
您在为哪一部分苦苦挣扎?看起来您甚至没有尝试创建字典或返回任何内容。
标签: python python-3.x dictionary