2015-02-10 68 views
-1

我有一個類似於以下文件:解析文本文件轉換成字典

Book 
Key: Norris2013 
Author: Elizabeth Norris 
Title: Unbreakable 
Publisher: Harper Collins Publishers 
Date: 2013 
Book 
Key: Rowling1997 
Author: J.K. Rowling 
Title: Harry Potter and the Philosopher's Stone 
Publisher: Bloomsbury Publishing 
Date: 1997 
Book 
Key: Dickens1894 
Author: Charles Dickens 
Title: A tale of two cities 
Publisher: Dodd, Mead 

編輯:我將數據輸入到字典中,像這樣:

newDict = {} 

with open('file.txt', 'r') as f: 
    for line in f: 
     splitLine = line.split() 
     newDict[splitLine[0]] = " ".join(splitLine[1:]) 
print (newDict) 

爲什麼只打印字典的最後一個條目?

+3

這是非常簡單的,但是,你需要表現出一定的工作我們就幹啥, – 2015-02-10 16:15:02

+1

閱讀線逐一前。如果這行是'Book',它將啓動一本新書,否則該行有一個鍵值字段,這些項用':'分隔。這些應該閱讀到字典或類的一個實例。現在把它翻譯成Python,你就完成了。 – 2015-02-10 16:21:26

+0

添加了我正在使用的代碼。但無法弄清楚爲什麼它只打印最後一個條目。 – user3528944 2015-02-10 17:44:18

回答

0

由於您多次重複使用相同的密鑰,您會一遍又一遍覆蓋字典。你可能想創建一個字典列表:

books = [] # Start with an empty list 
book = {}  # and an empty dictionary for the current book 
with open('file.txt', 'r') as f: 
    for line in f: 
     if line.strip() == "Book": # Are we at the start of a new book? Then... 
      if book:    # Add the current book (if there is one) to list 
       books.append(book) 
       book = {}   # Start a new book 
     else: 
      splitLine = line.strip().split() 
      book[splitLine[0]] = " ".join(splitLine[1:]) 
if book:       # Add final book to list 
    books.append(book) 
print (books)