以下是提示: 编写一个程序,该程序首先读取输入文件的名称,然后使用file.readines()方法读取输入文件.输入文件包含未排序的季数列表,其后是相应的电视节目.您的程序应该将输入文件的内容放入一个词典中,其中季数是关键字,电视节目列表是值(因为多个节目可能有相同的季数).
按关键字(从小到大)对词典进行排序,并将结果输出到名为out_keys.txt的文件中,用分号(;)分隔与同一关键字关联的多个电视节目.接下来,按值(字母顺序)对词典进行排序,并将结果输出到名为outputtitles.txt的文件中.
例如:如果输入为:
File1.txt和file1.txt的内容是:
20
枪击事件
30
辛普森一家
10
Will&;Grace
14
达拉斯
20
法律与秩序
12
谋杀,她写道
文件outputkeys.txt应包含:
10:Will&;Grace
12:谋杀,她写道
14:达拉斯
20:枪支;法律与秩序
30:辛普森一家
并且文件outputtitles.txt应该包含:
达拉斯
枪击事件
法律与秩序
谋杀,她写道
辛普森一家
Will&;Grace
这就是我所拥有的,但现在的问题是键没有按整数排序.因此,任何个位数的频道都没有得到正确的排序.在try 修复这个问题时,我遇到了字符串、整型和键错误.如何修复将电视节目频道排序为整数的代码?
file_name = input()
user_file = open(file_name)
output_list = user_file.readlines()
my_dict = {}
for index in range(len(output_list)):
if index % 2 == 0:
#if the line is even
dict_keys = output_list[index].strip('\n')
if dict_keys not in my_dict:
my_dict[dict_keys] = []
else:
my_dict[dict_keys].append(output_list[index].strip('\n'))
f = open('output_keys.txt', 'w')
sorted_keys = sorted(my_dict.keys())
output_file = ''
tv_show_list = []
for the_key in sorted_keys:
output_file += the_key + ': '
for tvshow in my_dict[the_key]:
output_file += tvshow + '; '
tv_show_list.append(tvshow)
output_file = output_file[:-2] + '\n'
f.write(output_file)
f.close()
f = open('output_titles.txt', 'w')
tv_show_list.sort()
sorted_list = ''
for tv_show in tv_show_list:
sorted_list += tv_show + '\n'
f.write(sorted_list)
f.close()