2

在我的介绍comp sci 课程的最后几天,我们开始创建字典。我们书中的一个家庭作业程序要求我们创建一些可以查找、添加、更改和删除一组姓名和电子邮件地址的东西。它要求我们腌制字典,但对我来说更重要的是它规定每次程序启动时,它都应该从文件中检索字典并取消腌制它。我不知道我是否将自己编码到一个角落,但我无法弄清楚如何用我迄今为止所做的事情来做到这一点。

我的代码:

import mMyUtils
import pickle
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5

def main():
    emails = {}
    choice = 0
    while choice != QUIT:
        choice = getMenuChoice()
        if choice == LOOK_UP:
            lookUp(emails)
        elif choice == ADD:
            add(emails)
        elif choice == CHANGE:
            change(emails)
        elif choice == DELETE:
            delete(emails)
        else:
            exit

def getMenuChoice():
    print()
    print('Name and Email Address Catalog')
    print('------------------------------')
    print('1. Look up an email address')
    print('2. Add a new email address')
    print('3. Change an email address')
    print('4. Delete an email address')
    print('5. Quit the program')
    print()

    choice = int(input('Enter the choice: '))
    while choice < LOOK_UP or choice > QUIT:
        choice = int(input('Enter a valid choice: '))

    return choice

def lookUp(emails):
    name = input('Enter a name: ')
    print(emails.get(name, 'Not found.'))

def add(emails):
    name = input('Enter a name: ')
    address = input('Enter an email address: ')
    if name not in emails:
        emails[name] = address
        pickle.dump(emails, open("emails.dat", "wb"))
    else:
        print('That entry already exists.')

def change(emails):
    name = input('Enter a name: ')
    if name in emails:
        address = input('Enter the new address: ')
        emails[name] = address
        pickle.dump(emails, open("emails.dat", "wb"))
    else:
        print('That name is not found.')

def delete(emails):
    name = input('Enter a name: ')
    if name in emails:
        del emails[name]
    else:
        print('That name is not found.')

main()

我知道我应该将我的 emails 变量设置为某种形式的 pickle.load,但我一生都无法弄清楚。mMyUtils 是我为 try/except 逻辑创建的库,一旦我得到新的东西,我就会把它放进去。

4

4 回答 4

2

如果您像这样保存字典:

pickle.dump(emails, open('emails.dat', 'wb'))

以下将加载它:

emails = pickle.load(open('emails.dat', 'rb'))
于 2012-12-18T12:35:40.593 回答
1

您必须先加载文件并解压缩数据,然后才能访问它,更改lookUp()为:

def lookUp(emails):
    with open("emails.dat", "rb") as fo:
        emails = pickle.load(fo)

    name = input('Enter a name: ')
    print(emails.get(name, 'Not found.'))
于 2012-12-18T12:37:41.430 回答
1

考虑自己使用 ast.literal_eval 而不是 pickle:http ://docs.python.org/2/library/ast.html#ast.literal_eval

>>>import ast
>>> print mydict
{'bob': 1, 'danny': 3, 'alan': 2, 'carl': 40}
>>> string="{'bob': 1, 'danny': 3, 'alan': 2, 'carl': 40}"
>>> type(string)
<type 'str'>
>>> type( ast.literal_eval(string) )
<type 'dict'>

要从文件中保存/读取字典,您可以像使用普通字符串一样进行操作。

于 2012-12-18T16:30:39.170 回答
0

问题是,我想我没有足够强调它,如果字典首先不存在我应该做的。设计文档指出,每次运行程序时都应该加载字典。好吧,如果您是第一次运行该程序,则没有要加载的字典,从而导致错误。我基本上通过使用 try/except 两次执行该功能来解决这个问题。

我的代码:

import mMyUtils
import pickle
import dictionaryGenerator
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5

def main():
    hasError = False
    try:
        emails = pickle.load(open('emails.dat', 'rb'))
        choice = 0
        while choice != QUIT:
            choice = getMenuChoice()
            if choice == LOOK_UP:
                lookUp(emails)
            elif choice == ADD:
                 add(emails)
            elif choice == CHANGE:
                change(emails)
            elif choice == DELETE:
                delete(emails)
            else:
                print("Good-bye!")
                exit
    except Exception as err:
        hasError = True
        mMyUtils.printError("Error: no such file",err)
        mMyUtils.writeToErrorLog()

    finally:
        if hasError:
            emails = {}
        choice = 0
        while choice != QUIT:
            choice = getMenuChoice()
            if choice == LOOK_UP:
                lookUp(emails)
            elif choice == ADD:
                add(emails)
            elif choice == CHANGE:
                change(emails)
            elif choice == DELETE:
                delete(emails)
            else:
                print("Good-bye!")
                exit





def getMenuChoice():
    print()
    print('Name and Email Address Catalog')
    print('------------------------------')
    print('1. Look up an email address')
    print('2. Add a new email address')
    print('3. Change an email address')
    print('4. Delete an email address')
    print('5. Quit the program')
    print()

    choice = int(input('Enter the choice: '))
    while choice < LOOK_UP or choice > QUIT:
        choice = int(input('Enter a valid choice: '))

    return choice

def lookUp(emails):

    name = input('Enter a name: ')
    print(emails.get(name, 'Not found.'))

def add(emails):
    name = input('Enter a name: ')
    address = input('Enter an email address: ')
    if name not in emails:
        emails[name] = address
        with open("emails.dat",  "wb") as infile:
            pickle.dump(emails, infile)

    else:
        print('That entry already exists.')

def change(emails):
    name = input('Enter a name: ')
    if name in emails:
        address = input('Enter the new address: ')
        emails[name] = address
        with open("emails.dat", "wb") as infile:
            pickle.dump(emails, infile)

    else:
        print('That name is not found.')

def delete(emails):
    name = input('Enter a name: ')
    if name in emails:
        del emails[name]
    else:
        print('That name is not found.')

main()
于 2012-12-18T14:28:24.533 回答