通过从文本文件中解析数据来重建数据库

时间:2015-03-19 13:38:03

标签: python database parsing database-design

O' Reilly Publications - 编程Python 第 - 17页,第2步:持续存储记录

嗯..我必须通过解析文本文件中的数据来重建数据库,并且我使用下面的代码。 " storeDbase()"方法完全有道理,我能够有效地实现它。然而,在尝试获得" loadDbase()"时,我完全陷入困境。功能工作。它没有任何意义,如果有人能向我解释,我真的很高兴。

谢谢。

文本文件.." people-file.txt"

Bob
AGE=> 42
JOB=> Developer
PAY=> 30000
NAME=> Bob Smith
endrec.
Steve
AGE=> 42
JOB=> Brewer
PAY=> 20000
NAME=> Bob Smith
endrec.
Sue
AGE=> 31
JOB=> Coder
PAY=> 50000
NAME=> Sue Willy
endrec.
Tom<br>
AGE=> 57
JOB=> Prez
PAY=> 90000
NAME=> Tom Heathern
endrec.
enddb.

* Database是DatabaseInfo模块中的字典。

    dbfilename = 'people-file.txt'
    ENDDB  = 'enddb.'
    ENDREC = 'endrec.'
    RECSEP = '=>'

    def storeDbase(db, dbfilename=dbfilename):
        "formatted dump of database to flat file"
        dbfile = open(dbfilename, 'w')
        for key in db:
            print(key, file=dbfile)
            print(key)
            for (name, value) in db[key].items():
                #print (value , "**")
                print(name + RECSEP , value, file=dbfile)
                print(name + RECSEP + repr(value))
            print(ENDREC, file=dbfile)
            print(ENDREC)
        print(ENDDB, file=dbfile)
        print(ENDDB)
        dbfile.close()

    def loadDbase(dbfilename=dbfilename):
        "parse data to reconstruct database"
        dbfile = open(dbfilename)
        import sys
        sys.stdin = dbfile
        db = {}
        key = input()
        while key != ENDDB:
            rec = {}
            field = input()
            while field != ENDREC:
                name, value = field.split(RECSEP)
                rec[name] = eval(value)
                field = input()
            db[key] = rec
            key = input()
        return db

    if __name__ == '__main__':
        from DatabaseInfo import Database
        storeDbase(Database)

1 个答案:

答案 0 :(得分:1)

while key != ENDDB:
    rec = {}
    field = input()
    while field != ENDREC:
        name, value = field.split(RECSEP)
        rec[name] = eval(value)
        field = input()
    db[key] = rec
    key = input()

可以解释为:

key := the first line
while the key isn't the end of the database
  | rec := initialize a new reccord
  | field := read the next line
  | while the field isnt the end of the reccord
  |   | key, value := splitting the field (and so the line)
  |   | add to the reccord the association key,value : reccord of key := value
  |   L field := next line
  L as we are here, we reached the end of the reccord, so save the reccord : database of key := reccord
as we are here, we reached the end of database line, so return the builded database

第一个while循环遍历记录,直到到达文件末尾。每个记录分析被委托给第二个循环,该循环遍历这些行,直到到达记录的末尾。