如何将文本文件(name1:hobby1 name2:hobby2)转换成这个(name1:hobby1,hobby2 name2:hobby1,hobby2)?

2024-06-25 07:07:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我是编程新手,需要一些帮助。我有一个包含很多名字和爱好的文本文件,看起来像这样:

Jack:crafting

Peter:hiking

Wendy:gaming

Monica:tennis

Chris:origami

Sophie:sport

Monica:design

有些名字和爱好是重复的。我试图让程序显示如下内容:

Jack: crafting, movies, yoga

Wendy: gaming, hiking, sport

到目前为止,这是我的程序,但最后的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]:

Tags: in程序formonica名字dictfilejack
3条回答

你可以试试这样的。我故意重写了这个,因为我想告诉你,你将如何在一个更“Python的方式”去做这件事。至少多用一点这种语言

例如,可以在字典中创建数组,以便更直观地表示数据。这样,以您想要的方式打印信息就更容易了

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概念的方向。如果你还没读完入门教程。。。我绝对推荐它

你可以试试这个

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

在本例中,我将使用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

相关问题 更多 >