对文件中的字典和列表进行排序

问题描述 投票:0回答:7

我必须编写一个程序,首先读取输入文件的名称,然后使用 file.readlines() 方法读取输入文件。输入文件包含未排序的季数列表,后跟相应的电视节目。然后我的程序应该将输入文件的内容放入字典中,其中季节数是键,电视节目列表是值(因为多个节目可能具有相同的季节数)。

然后,我需要按键(从小到大)对字典进行排序,并将结果输出到名为 output_keys.txt 的文件中,并用分号 (;) 分隔与同一键关联的多个电视节目。最后,按值(字母顺序)对字典进行排序,并将结果输出到名为 output_titles.txt 的文件

 def readFile(filename):

   dict = {}

   with open(filename, 'r') as infile:

       lines = infile.readlines()

       for index in range(0, len(lines) - 1, 2):

           if lines[index].strip()=='':continue

           count = int(lines[index].strip())

           show = lines[index + 1].strip()

           if count in dict.keys():

               show_list = dict.get(count)

               show_list.append(show)

               show_list.sort()

           else:

               dict[count] = [show]

           print(count,show)

   return dict

def output_keys(dict, filename):

   with open(filename,'w+') as outfile:

       for key in sorted(dict.keys()):

           outfile.write('{}: {}\n'.format(key,'; '.join(dict.get(key))))

           print('{}: {}\n'.format(key,'; '.join(dict.get(key))))

def output_titles(dict, filename):

   titles = []

   for title in dict.values():

       titles.extend(title)

   with open(filename,'w+') as outfile:

       for title in sorted(titles):

           outfile.write('{}\n'.format(title))

           print(title)

def main():

   filename = input()

   dict = readFile(filename)

   if dict is None:

       print('Error: Invalid file name provided: {}'.format(filename))

       return


   output_filename_1 ='output_keys.txt'

   output_filename_2 ='output_titles.txt'

   output_keys(dict,output_filename_1)

   output_titles(dict,output_filename_2)

main()

我不确定为什么当我尝试运行这段代码时会出现以下错误。

如有任何帮助,我们将不胜感激。谢谢!

python
7个回答
3
投票

这对我有用:

    def read_da_file(something):
        dict1 = {}
        with open(something, 'r') as infile:
            lines = infile.readlines()
            for index in range(0, len(lines) - 1, 2):
                if lines[index].strip() == '':
                    continue
                count = int(lines[index].strip())
                show = lines[index + 1].strip()
                if count in dict1.keys():
                    show_list = dict1.get(count)
                    show_list.append(show)
                else:
                    dict1[count] = [show]

        return dict1


    def output_keys(dict1, filename):
        with open(filename, 'w+') as q:
            for key in sorted(dict1.keys()):
                q.write('{}: {}\n'.format(key, '; '.join(dict1.get(key))))

                print('{}: {}'.format(key, '; '.join(dict1.get(key))))


    def output_titles(dict1, filename):
        titles = []

        for title in dict1.values():
            titles.extend(title)

        with open(filename, 'w+') as outfile:

            for title in sorted(titles):
                outfile.write('{}\n'.format(title))
                print(title)


    def main(x):
        file_name = x
        dict1 = read_da_file(file_name)
        if dict1 is None:
            print('Error: Invalid file name provided: {}'.format(file_name))

            return
        output_filename_1 = 'output_keys.txt'
        output_filename_2 = 'output_titles.txt'
        output_keys(dict1, output_filename_1)
        output_titles(dict1, output_filename_2)


    user_input = input()
    main(user_input)

1
投票

删除函数readfile中的show_list.sort()。这会导致在提示需要之前对节目名称进行排序。


1
投票

这是未来查询的正确代码。我目前正在参加 IT-140,并且通过了所有测试。如果您按照模块视频中的伪代码行进行操作,您将很容易得到这个。

file_name = input()
user_file = open(str(file_name))
output_list = user_file.readlines()
my_dict = {}
show_list = []
show_list_split = []
for i in range(len(output_list)):
    temp_list = []
    list_object = output_list[i].strip('\n')
    if (i + 1 < len(output_list) and (i % 2 == 0)):
        if int(list_object) in my_dict:
            my_dict[int(list_object)].append(output_list[i + 1].strip('\n'))
        else:
            temp_list.append(output_list[i + 1].strip('\n'))
            my_dict[int(list_object)] = temp_list
            
my_dict_sorted_by_keys = dict(sorted(my_dict.items()))
for x in my_dict.keys():
    show_list.append(my_dict[x])
for x in show_list:
    for i in x:
        show_list_split.append(i)
show_list_split = sorted(show_list_split)
f = open('output_keys.txt', 'w')
for key, value in my_dict_sorted_by_keys.items():
    f.write(str(key) + ': ')
    for item in value[:-1]:
        f.write(item + '; ')
    else:
        f.write(value[-1])
        f.write('\n')
        
f.close()
f = open('output_titles.txt', 'w')
for item in show_list_split:
    f.write(item + '\n')
f.close()

0
投票
def readInputFile(filename):
    shows_dict = {}
    file = open(filename, 'r')
    lines = file.readlines()
    for i in range(0, len(lines), 2):
        numOfSeasons = int(lines[i].strip())
        show = lines[i+1].strip()
        if numOfSeasons not in shows_dict.keys():
            shows_dict[numOfSeasons] = []
        shows_dict[numOfSeasons].append(show)
    return shows_dict


def outputSortedbyKeys(dict, filename):
    print("Sorting by keys: ")
    outfile = open(filename,'w')
    for key in sorted(dict.keys()):
        outfile.write('{}: {}\n'.format(key,'; '.join(dict.get(key))))
        print('{}: {}'.format(key,'; '.join(dict.get(key))))
    print(filename + " written successfully\n")


def outputSortedbyValues(dict, filename):
    print("Sorting by values: ")
    titles = []
    for key in dict.keys():
        for val in dict[key]:
            titles.append(val)
outfile = open(filename,'w')
for title in sorted(titles):
    outfile.write('{}\n'.format(title))
    print(title)
print(filename + " written successfully\n")

def main():
    filename = input("Enter the input filename: ") 
    shows_dict = readInputFile(filename)
    outputSortedbyKeys(shows_dict , 'output_keys.txt')
    outputSortedbyValues(shows_dict , 'output_titles.txt')

main()

0
投票

我目前正在参加 IT 140,@khild_of_the_koRn 的答案确实有效。在开发模式下,Zybooks 会说“(您的程序没有产生输出)”。但是,在提交模式下,它会通过。

我在这个实验上花了太多时间,因为我认为我做错了什么,因为开发模式一直说我的代码没有产生任何东西。

最后开始尝试其他代码,还是不行。当我找到这个答案时,我只是提交了它,因为我厌倦了在一个实验室上浪费时间,当它通过所有测试时,我松了一口气。有点自责,因为我不只是提交我的原始代码之一,它可能会通过或接近,然后我可以改进我的工作。

Zybooks 对于想要学习的人来说太挑剔了。我也关注他提到的同一个视频。


-2
投票

def readFile(文件名):

dict = {}

with open(filename, 'r') as infile:

   lines = infile.readlines()

   for index in range(0, len(lines) - 1, 2):

        if lines[index].strip()=='':continue

        count = int(lines[index].strip())
        show = lines[index + 1].strip()
        
        if count in dict.keys():
           show_list = dict.get(count)
           show_list.append(show)
        
        else:
        
           dict[count] = [show]
        
        print(count)
        print(show)

return dict

def output_keys(字典,文件名):

print()
with open(filename,'w+') as outfile:

   for key in sorted(dict.keys()):

       outfile.write('{}: {}\n'.format(key,'; '.join(dict.get(key))))

       print('{}: {}'.format(key,'; '.join(dict.get(key))))
print()   

def output_titles(字典,文件名): 标题=[]

for title in dict.values():

   titles.extend(title)

with open(filename,'w+') as outfile:

   for title in sorted(titles):

       outfile.write('{}\n'.format(title))

       print(title)

print()

文件名=输入() dict = readFile(文件名)

如果 dict 为 None: print('错误:提供的文件名无效:{}'.format(filename))

output1 ='output_keys.txt' 输出2 ='output_titles.txt' 输出键(字典,输出1) 输出标题(字典,输出2)


-3
投票

def readFile(文件名):

字典={}

将 open(filename, 'r') 作为 infile:

   lines = infile.readlines()

   for index in range(0, len(lines) - 1, 2):

       if lines[index].strip()=='':continue

       count = int(lines[index].strip())

       name = lines[index + 1].strip()

       if count in dict.keys():

           name_list = dict.get(count)

           name_list.append(name)

       else:

           dict[count] = [name]

       print(count,name)

返回字典

def output_keys(字典,文件名):

使用 open(filename,'w+') 作为输出文件:

   for key in sorted(dict.keys()):

       outfile.write('{}: {}\n'.format(key,'; ' .join(dict.get(key))))

       print('{}: {}\n'.format(key,'; ' .join(dict.get(key))))  

def output_titles(字典,文件名):

标题=[]

对于 dict.values() 中的标题:

   titles.extend(title)

使用 open(filename,'w+') 作为输出文件:

   for title in sorted(titles):

       outfile.write('{}\n'.format(title))

       print(title)

def main():

filename = input('请输入输入文件名:')

dict = readFile(文件名)

如果 dict 为 None:

   print('Error: Invalid file name provided: {}'.format(filename))

   return

打印(字典)

output_filename_1 ='output_keys.txt'

output_filename_2 ='output_titles.txt'

output_keys(字典,output_filename_1)

输出标题(字典,输出文件名_2)

主要()

这是正确的脚本

© www.soinside.com 2019 - 2024. All rights reserved.