list - Text document to dictionary Python -


okay, have text file "relationships.txt" has following inside:

elizabeth: peter, angela, thomas mary: tom angela: fred, alison alison: beatrice, dick, harry  mother elizabeth mother tom mother angela mother gurgle 

the first 4 lines set mother: child, child, child etc bottom 4 lines statements should return result. eg:

mother elizabeth should return: mother not known

while

mother tom should return: mary

i meant create dictionary allow work, have no clue do. appreciated.

so far have following:

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) 

i wasn't able finish, it's late, should going, binding children mothers list of tuples.
it's kinda hacky, structure of file rather weird (and still don't see why have use that).

import re  rel = {}  open("test/relationships.txt") f:     line in f:         # valid mother: child, child, [..]         try:             # remove newliens , spaces             line = re.sub('[\n ]', '', line)             mother = line.split(':')[0]             children = line.split(':')[1].split(',')              # append tuple (child, mother)             c in children:                 rel.append((c, mother))          # else, ignore         except:             continue  print rel 

gives:

[('peter', 'elizabeth'), ('angela', 'elizabeth'), ('thomas', 'elizabeth'), ('tom', 'mary'), ('fred', 'angela'), ('alison', 'angela'), ('beatrice', 'alison'), ('dick', 'alison'), ('harry', 'alison')]

so remains parse name of children in mother child, , see if child key in list.


Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -