使用文件更新词典

2024-04-16 09:13:15 发布

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

我有以下文件,我需要更新两个字典。其中一个映射一个人的朋友,另一个映射一个人的网络。文件格式如下: 普里切特,杰伊 普里切特,格洛丽亚 德尔加多,曼尼 邓菲,克莱尔

Dunphy, Claire
Parent Teacher Association
Dunphy, Phil
Pritchett, Mitchell
Pritchett, Jay

Scrooge, McDuck

Delgado, Manny
Chess Club
Pritchett, Gloria
Pritchett, Jay
Dunphy, Luke

Pritchett, Mitchell
Law Association
Dunphy, Claire
Tucker, Cameron
Dunphy, Luke

Dunphy, Alex
Orchestra
Chess Club
Dunphy, Luke

Tucker, Cameron
Clown School
Wizard of Oz Fan Club
Pritchett, Mitchell
Pritchett, Gloria

Dunphy, Haley Gwendolyn
D-Money, Dylan
D-Cat, Gilbert

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

D-Money, Dylan
D-Cat, Chairman

Dunphy, Haley Gwendolyn

Pritchett, Gloria
Parent Teacher Association
Pritchett, Jay 
Tucker, Cameron
Delgado, Manny

Dunphy, Luke
Delgado, Manny
Dunphy, Alex
Dunphy, Phil
Pritchett, Mitchell

我使用readline()方法读取文件并相应地更新字典。仅供参考,字典如下所示:

person_to_friends = {'Jay Pritchett': ['Claire Dunphy', 'Gloria 
Pritchett', 'Manny Delgado']...

person_to_networks = {'Claire Dunphy': ['Parent Teacher Association'], 
'Manny Delgado': ['Chess Club']...

我有这个代码到目前为止,我试图读取文件,但我有麻烦,因为不是使第一个名字的关键,它使每一个名字,直到换行键。你知道吗

friends = []
line = profiles_file.readline()
while line != '':
    profiles = format_name(line)
    if not profiles in person_to_friends:
        person_to_friends[profiles] = []
    line = profiles_file.readline()
    if not ',' in line:
        network = line
        line = profiles_file.readline()
    else:
        if format_name(line) != '' and format_name(line) not in person_to_friends[profiles]:
            person_to_friends[profiles].append(format_name(line))
            line = profiles_file.readline()


return person_to_friends

对于引用格式,\u name只是我编写的一个函数,用于确保文件中的名称采用“Firstname Lastname”格式,并删除换行符。你知道吗


Tags: 文件tonamereadlinelineprofilespersonluke