学习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')]}
答案 0 :(得分:2)
一种方法是使用csv
模块和setdefault
方法dict
:
>>> import csv
>>> with open('data.csv') as f:
... d = {}
... reader = csv.reader(f)
... header = next(f) # skip first line, save it if you want to
... for line in reader:
... artist, *rest = line
... d.setdefault(artist,[]).append(tuple(rest))
...
>>> d
{'Leonardo da Vinci': [('Mona Lisa', '1503', '76.8', '53.0', 'oil paint', 'France'), ('The Last Supper', '1495', '460.0', '880.0', 'tempera', 'Italy')]}
更加pythonic的方式是使用defaultdict
:
>>> from collections import defaultdict
>>> with open('data.csv') as f:
... d = defaultdict(list)
... reader = csv.reader(f)
... header = next(f) # skip header
... for line in reader:
... artist, *rest = line
... d[artist].append(rest)
...
>>> d
defaultdict(<class 'list'>, {'Leonardo da Vinci': [('Mona Lisa', '1503', '76.8', '53.0', 'oil paint', 'France'), ('The Last Supper', '1495', '460.0', '880.0', 'tempera', 'Italy')]})
>>>
找出获得所需数据类型的最佳方法是留作练习......显然这一切都是从一开始。
答案 1 :(得分:0)
您的输入文件是CSV文件(以逗号分隔的值)。有一个名为csv
的模块用于阅读它们。
import csv
import ast
def our_function(filename):
output = {}
with open(filename) as f:
r = csv.reader(f)
_ = next(r) #ignore the first line
for line in r:
head, *tail = map(ast.literal_eval, line) #make values the right types
if head in output:
output[head].append(tuple(tail))
else:
output[head] = [tuple(tail)]
return output
ast.literal_eval
会接受'"Mona Lisa"'
,'1234'
等输入,并返回'Mona Lisa'
和1234
等输出
答案 2 :(得分:0)
使用csv.reader
对象和enumerate
函数的解决方案:
import csv
picture_info = {}
# let's say: `pictures.csv` is your initial file
with open('pictures.csv', 'r', newline='\n') as fh:
r = csv.reader(fh)
for k, line in enumerate(r):
if k == 0: continue
if not picture_info.get(line[0], None):
picture_info[line[0]] = [tuple(line[1:])]
else:
picture_info[line[0]].append(tuple(line[1:]))
print(picture_info)
输出:
{'Leonardo da Vinci': [('Mona Lisa', '1503', '76.8', '53.0', 'oil paint', 'France'), ('The Last Supper', '1495', '460.0', '880.0', 'tempera', 'Italy')]}