【发布时间】:2013-05-15 15:33:27
【问题描述】:
好的,我有一个名为“relationships.txt”的文本文件,其中包含以下内容:
Elizabeth: Peter, Angela, Thomas
Mary: Tom
Angela: Fred, Alison
Alison: Beatrice, Dick, Harry
mother Elizabeth
mother Tom
mother Angela
mother Gurgle
前4行设置为Mother:Child、Child、Child等 底部 4 行是应该返回结果的语句。例如:
mother Elizabeth 应该返回:Mother not known
同时
mother Tom 应该返回:Mary
我打算创建一个字典来让它工作,但我不知道该怎么做。帮助表示赞赏。
到目前为止,我有以下内容:
test_file = open('relationships.txt', 'w')
test_file.write('''Elizabeth: Peter, Angela, Thomas
Mary: Tom
Angela: Fred, Alison
Alison: Beatrice, Dick, Harry
mother Elizabeth
mother Tom
mother Angela
mother Gurgle
''')
test_file.close()
def create_list():
open_file = open('relationships.txt', 'r')
lines = open_file.readlines()
return(lines)
【问题讨论】:
-
完全不知道?你什么都没试过?
-
这可能是个不错的起点:docs.python.org/2/tutorial/…
-
人们不会为你解决问题。您需要发布代码,然后人们会帮助您解决您不理解或您做错了什么。
-
我确实知道我需要做什么。我需要将整个文件读入行列表。然后,我可以找到分隔文件两个部分的空白行,并将一个子行列表传递给一个函数,该函数返回一个字典,将孩子的名字映射到他们的母亲,另一个子列表传递给一个处理列表的函数查询。但只是有点不确定如何做到这一点:S
-
我明白了,我会在一分钟内发布我到目前为止所做的事情
标签: python list text dictionary document