Сортировка словарей и списков из файла

#python

#python

Вопрос:

Мне нужно написать, чтобы написать программу, которая сначала считывает имя входного файла, а затем считывает входной файл с помощью метода 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()
 

Я не уверен, почему этот код выдает мне ошибку ниже, когда я пытаюсь его запустить.
введите описание изображения здесь

Любая помощь приветствуется. Спасибо!

Комментарии:

1. Это может быть лучшим вопросом для тех, кто написал тестовые примеры; похоже, ожидается, что некоторые, но не все, выходные строки будут отсортированы в обратном алфавитном порядке или даже в случайном порядке, основанном на expected output том, что вы включили

2. Также стоит упомянуть: не называйте свой словарь dict , так как это затеняет встроенный dict объект и может вызвать проблемы

Ответ №1:

Это сработало для меня:

     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. Пожалуйста, не публикуйте только код в качестве ответа, но также предоставьте объяснение того, что делает ваш код и как он решает проблему вопроса. Ответы с объяснением обычно более полезны и более высокого качества и с большей вероятностью привлекут голоса

Ответ №2:

удалите show_list.sort() из функции readfile. Это приводит к сортировке имен шоу до того, как оно потребуется для запроса.

Ответ №3:

Это правильный код для любых будущих запросов. В настоящее время я беру 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()
 

Комментарии:

1. для меня это ничего не дает

2. Извините, я только сейчас вижу этот комментарий. Используете ли вы Zybooks? Потому что этот код прошел все тесты.

Ответ №4:

 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 successfullyn")


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 successfullyn")

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()
 

Ответ №5:

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(dict, filename):

 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(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)

print()
 

filename = input()
dict = ReadFile(имя файла)

если значение dict равно None: print(‘Ошибка: указано неверное имя файла: {}’.format(имя файла))

output1 =’output_keys.txt ‘ output2 =’output_titles.txt ‘output_keys(dict,output1) output_titles(dict,output2)

Ответ №6:

def ReadFile(имя файла):

dict = {}

с open(filename, ‘r’) в качестве файла:

    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)
 

возвращает dict

def output_keys(dict, filename):

с 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, filename):

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
 

печать (dict)

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()

Это правильный сценарий