gpt4 book ai didi

python - 读取csv文件,解析数据,并存储在字典中

转载 作者:行者123 更新时间:2023-12-01 00:19:40 24 4
gpt4 key购买 nike

我有一个文件,其中包含广播电台、艺术家和播放时间最近播放的歌曲,格式如下:“2019 年 11 月 4 日 8:02 PM”、“Wagon Wheel”、“Darius Rucker”。我试图将此文件的内容存储在字符串变量 playlist_csv 中,使用 splitlines() 将记录存储在变量行中,然后迭代各行以将数据存储在字典中。键应该是时间戳的日期时间对象,值应该是歌曲和艺术家的元组:{datetime_key: (song, Artist)}

以下是该文件的摘录:

"November 4, 2019 8:02 PM","Wagon Wheel","Darius Rucker" 
"November 4, 2019 7:59 PM","Remember You Young","Thomas Rhett"
"November 4, 2019 7:55 PM","Long Hot Summer","Keith Urban"

这就是所需的字典的样子:

{datetime.datetime(2019, 11, 4, 20, 2): ('Wagon Wheel', 'Darius Rucker'), 
datetime.datetime(2019, 11, 4, 19, 59): ('Remember You Young', 'Thomas Rhett'),
datetime.datetime(2019, 11, 4, 19, 55): ('Long Hot Summer', 'Keith Urban')}

这是我到目前为止的代码:

# read the file and store content in string variable playlist_csv
with open('playlist.txt', 'r') as csv_file:
playlist_csv = csv_file.read().replace('\n', '')
# use splitlines() method to store records in variable lines (it is list)
split_playlist = playlist_csv.splitlines()
# iterate through lines to store data in playlist_dict dictionary
playlist_dict = {}
for l in csv.reader(split_playlist, quotechar='"', delimiter=',',
quoting=csv.QUOTE_ALL, skipinitialspace=True):
dt=datetime.strptime(l[0], '%B %d, %Y %I:%M %p')
playlist_dict[l[dt]].append(dt)
print(playlist_dict)

但是,当我尝试将此数据存储在字典中时,我不断遇到错误(特别是修改代码时“'datetime.datetime'对象不可下标”和“列表索引必须是整数或切片”)。

感谢您的帮助!

最佳答案

您首先尝试拆分 csv 文件似乎是不必要的 - csv.reader 会为您处理所有这些事情。而不是 playlist_dict[l[dt]].append(dt) 你需要类似 playlist_dict[dt].append((song, Artist)) 的东西。这应该有效:

with open('playlist.txt', 'r') as csv_file:
playlist = {}
for time, song, artist in csv.reader(csv_file):
time = datetime.strptime(time, '%B %d, %Y %I:%M %p')
if time in playlist:
playlist[time].append((song, artist))
else:
playlist[time] = [(song, artist)]

(您提供给 csv.reader 的可选参数可能也不需要 - 默认值应该适用于您给出的输入类型。)

或者,如果您在每个日期时间只有一首可能的歌曲/艺术​​家,那么您不需要列表并且可以执行此操作(这似乎是您正在寻找的输出):

with open('playlist.txt', 'r') as f:
playlist = {datetime.strptime(time, '%B %d, %Y %I:%M %p'): (song, artist)
for time, song, artist in csv.reader(f)}

关于python - 读取csv文件,解析数据,并存储在字典中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59043893/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com