我有一个文件,其中包含一个广播电台,艺术家最近播放的歌曲以及该格式播放的时间:“ 2019年11月4日晚上8:02”,“货车车轮”,“达里斯·鲁克”。我试图将此文件的内容存储在字符串变量playlist_csv中,使用splitlines()将记录存储在变量行中,然后遍历这些行以将数据存储在字典中。键应该是时间戳记的datetime对象,值应该是歌曲和歌手的元组:{datetime_key:(歌曲,歌手)}
这是文件摘录:
"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'对象不可下标”,并且在修改代码时“列表索引必须是整数或切片”)。
感谢您的帮助!
答案 0 :(得分:2)
您似乎不需要首先尝试拆分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)}
答案 1 :(得分:0)
由于事实证明,这可能是此情况下的更好选择,这是使用Pandas的解决方案。作为奖励,它可以计算每首歌曲之间的时间。
import pandas as pd
df = pd.read_csv('../resources/radio_songs.csv', dtype={'song_name': str, 'artist': str},
parse_dates=[0], header=None, names=['time_played', 'song_name', 'artist'])
df['time_diff'] = df['time_played'].diff(periods=-1)
DataFrame输出:
time_played song_name artist time_diff
0 2019-11-04 20:02:00 Wagon Wheel Darius Rucker 00:03:00
1 2019-11-04 19:59:00 Remember You Young Thomas Rhett 00:04:00
2 2019-11-04 19:55:00 Long Hot Summer Keith Urban NaT
如果出于某种原因需要它,这是一种重新创建字典格式的有趣方法:
tuples_dict = dict(zip(df['time_played'], zip(df['song_name'], df['artist'])))
输出:
{Timestamp('2019-11-04 20:02:00'): ('Wagon Wheel', 'Darius Rucker'), Timestamp('2019-11-04 19:59:00'): ('Remember You Young', 'Thomas Rhett'), Timestamp('2019-11-04 19:55:00'): ('Long Hot Summer', 'Keith Urban')}