将文本文件解析为词典

2024-06-25 05:18:18 发布

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

我有一个类似于以下内容的文件:

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

编辑:我将数据输入字典,如下所示:

^{pr2}$

为什么它只打印出词典的最后一条?在


Tags: 文件keydatetitlepublisherauthornorrisbook
1条回答
网友
1楼 · 发布于 2024-06-25 05:18:18

因为多次重复使用相同的键,所以您一次又一次地重写字典。您可能需要创建字典列表:

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)

相关问题 更多 >