文本文档到词典Python

2024-09-24 00:25:13 发布

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

好吧,我有一个文本文件关系.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)

Tags: testtxtchildthomasopenfredfilepeter
1条回答
网友
1楼 · 发布于 2024-09-24 00:25:13

我没能完成,已经很晚了,但这应该能让你继续,用元组列表把孩子和他们的母亲绑定起来。
这有点黑客,但你的文件结构是相当奇怪的(我仍然不明白你为什么要使用这样的东西)。你知道吗

import re

rel = {}

with open("test/relationships.txt") as f:
    for line in f:
        # Valid Mother: Child, Child, [..]
        try:
            # Remove newliens and spaces
            line = re.sub('[\n ]', '', line)
            mother = line.split(':')[0]
            children = line.split(':')[1].split(',')

            # Append a tuple (child, mother)
            for c in children:
                rel.append((c, mother))

        # Something else, ignore for now
        except:
            continue

print rel

提供:

[('Peter', 'Elizabeth'), ('Angela', 'Elizabeth'), ('Thomas', 'Elizabeth'), ('Tom', 'Mary'), ('Fred', 'Angela'), ('Alison', 'Angela'), ('Beatrice', 'Alison'), ('Dick', 'Alison'), ('Harry', 'Alison')]

所以剩下的就是解析mother child中子级的名称,看看child是否是列表中的键。你知道吗

相关问题 更多 >