好吧,我有一个文本文件关系.txt“里面有以下内容:
Elizabeth: Peter, Angela, Thomas
Mary: Tom
Angela: Fred, Alison
Alison: Beatrice, Dick, Harry
mother Elizabeth
mother Tom
mother Angela
mother Gurgle
前4行设置为母亲: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)
我没能完成,已经很晚了,但这应该能让你继续,用元组列表把孩子和他们的母亲绑定起来。
这有点黑客,但你的文件结构是相当奇怪的(我仍然不明白你为什么要使用这样的东西)。你知道吗
提供:
[('Peter', 'Elizabeth'), ('Angela', 'Elizabeth'), ('Thomas', 'Elizabeth'), ('Tom', 'Mary'), ('Fred', 'Angela'), ('Alison', 'Angela'), ('Beatrice', 'Alison'), ('Dick', 'Alison'), ('Harry', 'Alison')]
所以剩下的就是解析
mother child
中子级的名称,看看child是否是列表中的键。你知道吗相关问题 更多 >
编程相关推荐