2013-05-15 44 views
-3

好吧,我有一個文本文件,「relationships.txt」具有以下內:文本文檔到字典中的Python

Elizabeth: Peter, Angela, Thomas 
Mary: Tom 
Angela: Fred, Alison 
Alison: Beatrice, Dick, Harry 

mother Elizabeth 
mother Tom 
mother Angela 
mother Gurgle 

第4行設置爲母親:小孩,兒童,兒童等 底部的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) 
+1

完全不知道呢?你還沒有嘗試過任何東西? – Blender

+2

這可能是一個良好的開端:http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files – monkut

+0

人們不會爲你做你的問題。你需要發佈代碼,然後人們會幫助你解決你不明白的問題或者錯誤的做法。 –

回答

0

我沒能完成,它的晚,但是這應該讓你去,結合孩子們給他們的母親與一個元組列表。
它有點哈克,但你的文件的結構是相當奇怪的(我仍然不明白爲什麼你會使用類似的東西)。

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解析孩子的名字,看看孩子是在列表中的一個關鍵。

+0

感謝您的幫助,我得到以下錯誤雖然 回溯(最近通話最後一個): 文件「C:\用戶\用戶\文檔\ untitled-1.py」 18行,在 語法錯誤: print rel:C:\ Users \ user \ Documents \ untitled-1.py,line 189 – user2383844

+0

^忘記標記你 – user2383844

+0

@ user2383844從貼上剪下來的東西。無論如何,它應該很容易爲自己修復。我建議你在嘗試做這樣的事情之前學習一些Python :)我可以推薦[Codeacademy的Python課程](http://www.codecademy.com/tracks/python)。 – timss

相關問題