def parse_actor_data(actor_data):
while 1:
line = actor_data.readline().strip()
if line.count('-') > 5:
break
actor_movie = {}
values = []
actor_name = ''
running_list = []
movie = []
for line in actor_data:
position = line.find(')')
running = line[:position + 1]
value = running.split('\t')
for k in value:
if k != '':
running_list.append(k)
actor_name_list = value[0].split(',')
actor_name = actor_name_list[0] + actor_name_list[-1]
for i in range(len(running_list)):
if value[0] == running_list[i]:
position2 = i
movie = running_list[position2+1:]
actor_movie[actor_name] = movie
check = actor_movie.keys()
for c in range(len(check)):
if len(check[c]) < 1:
actor_movie.pop(check[c])
return actor_movie
我现在遇到的问题是,只有第一项电影被添加到actor_movie,任何人都可以提供帮助吗?我已经尝试了很久,我已经认真地不知道为什么这不起作用......
答案 0 :(得分:1)
每次你跑:
actor_movie[actor_name] = movie
你正在覆盖与该演员相关联的最后一部电影。尝试这样的东西,而不是存储电影列表,而不仅仅是单个值:
try:
actor_movie[actor_name].append(movie)
except KeyError:
actor_movie[actor_name] = [movie]
还有其他方法(defaultdict
,dict.setdefault
等)可以做同样的事情,但这应该可以帮助您启动并运行。