Как сделать текстовый файл (name1: hobby1 name2: hobby2) в это (name1: hobby1, hobby2 name2: hobby1, hobby2)?

1

Я новичок в программировании, и мне нужна помощь. У меня есть текстовый файл с большим количеством имен и хобби, который выглядит примерно так:

Джек: крафт

Петр: туризм

Венди: игровой

Моника: теннис

Крис: Оригами

Софи спорт

Моника: дизайн

Некоторые имена и хобби повторяются. Я пытаюсь сделать отображение программы примерно так:

Джек: крафтинг, фильмы, йога

Венди: игры, туризм, спорт

Это моя программа до сих пор, но 4 строки с конца неверны.

def create_dictionary(file):
newlist = []
dict = {}
file = open("hobbies_database.txt", "r")
hobbies = file.readlines()
for rows in hobbies:
    rows1 = rows.split(":")
    k = rows1[0] # nimi
    v = (rows1[1]).rstrip("\n") # hobi
    dict = {k: v}
    for k, v in dict.items():
        if v in dict[k]:
Теги:

3 ответа

1

вы можете попробовать это

data = map(lambda x:x.strip(), open('hobbies_database.txt'))
tmp = {}
for i in data:
    k,v = i.strip().split(':')
    if not tmp.get(k, []):
        tmp[k] = []
    tmp[k].append(v)
for k,v in tmp.iteritems():
    print k, ':', ','.join(v)

выход:

Monica : tennis,design
Jack : crafting
Wendy : gaming
Chris : origami
Sophie : sport
Peter : hiking
1

В этом случае я бы использовал defaultdict.

import sys 
from collections import defaultdict


def create_dictionary(inputfile):
    d = defaultdict(list)
    for line in inputfile:
        name, hobby = line.split(':', 1)
        d[name].append(hobby.strip())
    return d


with open(sys.argv[1]) as fp: 
    for name, hobbies in create_dictionary(fp).items():
        print(name, ': ', sep='', end='')
        print(*hobbies, sep=', ')

Ваш пример даст мне следующий результат:

Sophie: sport
Chris: origami
Peter: hiking
Jack: crafting
Wendy: gaming
Monica: tennis, design
1

Вы могли бы попробовать что-то вроде этого. Я преднамеренно переписал это, поскольку я пытаюсь показать вам, как вы это сделаете более "путинским способом". По крайней мере, использование языка немного больше.

Например, вы можете создавать массивы в словарях для более интуитивного представления данных. Тогда будет легче распечатать информацию так, как вы хотите.

def create_dictionary(file):

    names = {} # create the dictionary to store your data

    # using with statement ensures the file is closed properly
    # even if there is an error thrown
    with open("hobbies_database.txt", "r") as file:

        # This reads the file one line at a time
        # using readlines() loads the whole file into memory in one go
        # This is far better for large data files that wont fit into memory
        for row in file:

            # strip() removes end of line characters and trailing white space
            # split returns an array [] which can be unpacked direct to single variables
            name, hobby = row.strip().split(":")

            # this checks to see if 'name' has been seen before
            # is there already an entry in the dictionary
            if name not in names:

                # if not, assign an empty array to the dictionary key 'name'
                names[name] = []

            # this adds the hobby seen in this line to the array
            names[name].append(hobby)

    # This iterates through all the keys in the dictionary
    for name in names:

        # using the string format function you can build up
        # the output string and print it to the screen

        # ",".join(array) will join all the elements of the array
        # into a single string and place a comma between each

        # set(array) creates a "list/array" of unique objects
        # this means that if a hobby is added twice you will only see it once in the set

        # names[name] is the list [] of hobby strings for that 'name'
        print("{0}: {1}\n".format(name, ", ".join(set(names[name]))))

Надеюсь, что это поможет, и, возможно, укажет вам в сторону еще нескольких концепций Python. Если вы еще не прошли вступительный курс, я бы определенно рекомендовал его.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню