【问题标题】:Text document to dictionary Python文本文档到字典 Python
【发布时间】: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


【解决方案1】:

我没能完成,已经很晚了,但这应该能让你开始,用元组列表将孩子绑定到他们的母亲。
这有点 hacky,但你的文件结构相当奇怪(我仍然不明白为什么你必须使用这样的东西)。

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中的children的名字,看看child是否是列表中的key。

【讨论】:

  • 感谢您的帮助,虽然 Traceback(最近一次调用最后一次)出现以下错误:文件“C:\Users\user\Documents\untitled-1.py”,第 18 行,在 语法错误:打印 rel: C:\Users\user\Documents\untitled-1.py, line 189
  • @user2383844 从粘贴中剪掉了一些东西。无论如何,它应该很容易为自己修复。我敦促你在尝试做这样的事情之前实际学习一些 Python :) 我可以推荐Codeacademy's Python course
  • 感谢您的帮助。我今天实际上已经弄清楚了整个事情,但是感谢您的帮助。 :)
  • @user2383844 如果你知道了,你应该answer your own question
猜你喜欢
  • 2018-01-11
  • 1970-01-01
  • 1970-01-01
  • 2021-08-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多