在python中创建负载配置文件功能

时间:2012-04-01 21:15:39

标签: python dictionary

好吧我正在尝试创建一个更新/创建两个词典的函数,以包含打开文件中的数据。

示例文本文件如下所示:

Dunphy, Claire  # Name of the person
Parent Teacher Association  # The networks person is associated with
Dunphy, Phil  # List of friends
Pritchett, Mitchell
Pritchett, Jay

Dunphy, Phil
Real Estate Association
Dunphy, Claire
Dunphy, Luke

Pritchett, Jay
Pritchett, Gloria
Delgado, Manny
Dunphy, Claire

def load_profiles(profiles_file, person_to_friends, person_to_networks):
  • 假设profiles_file已经全部打开,因此无需传递参数来打开文件

  • 人对朋友是一本字典,每个键都是一个人(str),每个值都是那个人的朋友(strs列表)。

  • 网络人员是一个字典,每个键都是一个人(str),每个值都是人所属的网络(strs列表)。

所以我想在子函数/辅助函数中分解这个问题会更容易,一个函数可以创建人员到朋友字典,另一个函数可以创建人员到网络字典。

到目前为止,对于朋友的功能,我想出了:

def person_to_friend(profiles_file):

    person = {}
    friends = []

    for name in profiles_file:
        name = name.strip(). split('\n')

        if "," in name and name not in person.keys():
            person[key].append(name)

    return person

但这会返回一个空字典,不知道我做错了什么。也不确定如何将朋友添加为人的值。

3 个答案:

答案 0 :(得分:1)

尽管你的原始问题陈述中存在缩进问题(这会引发语法错误,你很快就会解决),但你的person_to_friend函数在其字典调用中有一个错误:person[key].append(name)应该读{ {1}}。否则看起来很好。

我相信您的设计可以通过开发一个将person[key] = name连接到persons的更强大的关系模型来改进,但是您的家庭作业的整个目的是帮助教您如何运作!所以,我会变得腼腆,而不是让农场知道如何重新设计你的应用程序,只解决这里的技术说明。

我还会检查Python csv以解析您的输入文件内容,因为当您尝试完成设计时,它会为您的底层数据提供更简单,更健壮的模型。

否则,我只想感谢您提供一个精彩的示例,说明如何在StackOverflow上正确起草friends问题。除了格式化之外,这是清晰,简洁,注重细节的,并且在您完成当前课程时,作为程序员的能力非常好。祝你好运!

答案 1 :(得分:1)

您的“帮助程序”函数尝试迭代整个文件。虽然使用单独的函数向词典添加条目并不是一个坏主意,但它应该在单个循环中完成,例如:

def load_profiles(profiles_file, person_to_friends, person_to_networks):
    friends = []
    networks = []
    for line in profiles_file:
        if not line.strip(): # we've just finished processing an entry, 
                             # need to get ready for the next one
            person_to_friends[name] = friends
            person_to_networks[name] = networks
            friends = []
            networks = []
        else:
            if friends == networks == []: # we haven't read anything yet,
                name = line               # so this must be the name
            elif ',' in line:
                friends.append(line)
            else:
                associations.append(line)

这可能过度简化了(例如,它没有检查网络是否在朋友面前列出),但是已经有太多的代码来回答家庭作业问题了。我希望它能得到补偿,因为我没有测试过它:)干杯。

答案 2 :(得分:0)

你是从for循环中返回的,所以基本上你在第一次迭代后返回。

另外,我不太了解name = name.strip().split('\n')name已经是profiles_file的一行吗? 此外,请确保key中的person[key].append(name)存在且person[key]是一个列表。

我认为你应该重新考虑一下你的算法。

编辑: 也许这样的事情对你有用:

f = open(profiles_file)
person = {}
friends = []
groups = f.read().split('\n\n')
for g in groups:
    g = g.split('\n')
    person[g[0]] = []
    for friend in g[1:]:
        if ',' in friend:
             person[g[0]].append(friend)

当然,为了在不打开文件的情况下执行此操作,只需创建2个词典或向现有词典添加另一个键,例如person[key]['friends']person[key]['networks']。然后将else放到最后if