我如何提取数据是这个CSV作为一个python字典没有导入包?数据样本:
用户id;"ISBN";"Book-Rating"276725年,"034545104 x";"0";276726;"0155061224","5";276727;"0446520802";"0";276729;"052165615 x"3">
def loadRatings():
# Get bookratings
try:
bookR = {}
for line in open('booktext.csv'):
(id,title) = line.split(';')[0:2]
bookR[id] = title
return bookR
except IOError as ioerr:
print('File error: ' + str(ioerr))
print(loadRatings())
but i need my result to be like
bookR = {User-ID: 276725, ISBN: 034545104X, Rating: 0}
此代码将返回
with open("booktext.csv") as f:
for i, line in enumerate(f):
# skip header
if i == 0:
continue
row_lst = line.replace("n","").replace('"','').split(";")
if len(row_lst) == 3:
bookR = {
"User-ID": row_lst[0],
"ISBN": row_lst[1],
"Rating": row_lst[2]
}
print(bookR)
{"用户id","276725","ISBN":"034545104 x","等级":' 0 '}
{"用户id","276726","ISBN":"0155061224","等级":"5"}
{"用户id","276727","ISBN":"0446520802","等级":' 0 '}
{"用户id","276729","ISBN":"052165615 x","等级":"3"}
在处理文件时,你总是应该使用上下文管理器with
,除非你真的知道并且有很好的理由不这样做。详见https://stackoverflow.com/a/3012921/20646982
描述在您正在寻找的内容方面是模糊的,不清楚它应该是所有项目的单个字典,还是只是单独的行。如果您需要一个普通的dict
,您可以使用这种简单的方法,只需稍后根据您需要的数据类型进行少量格式化。我设法重建了如下的结果:
with open('ex.csv',newline="") as f:
d = list(f.read().split(' '))
keys = d[0].split(';')
values = d[1:]
book = {}
for idx, key in enumerate(keys):
book[key] = []
for i in range(len(values)):
book[key].append(values[i].split(';')[idx])
生成结果:
{'User-ID': ['276725', '276726', '276727', '276729'],
'"ISBN"': ['"034545104X"', '"0155061224"', '"0446520802"', '"052165615X"'],
'"Book-Rating"': ['"0"', '"5"', '"0"', '"3"']}
import csv
filename ="Geeks.csv"
# opening the file using "with"
# statement
with open(filename, 'r') as data:
for line in csv.DictReader(data):
print(line)