使用Python的pickle打开并保存字典

2024-05-20 18:22:24 发布

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

在我的comp-sci入门课的最后几天里,我们要创建字典。书中的家庭作业程序要求我们创建一些可以查找、添加、更改和删除一组姓名和电子邮件地址的内容。它要求我们对字典进行pickle操作,但对我来说更重要的是,它规定每次程序启动时,它都应该从文件中检索字典并取消对它的pickle操作。我不知道我是否把自己编入了一个角落,但我不知道如何利用我目前所做的来做到这一点。

我的代码:

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 logic创建的一个库,一旦新的东西开始工作,我就把它放进去。


Tags: nameaninputif字典addressemaildef
1条回答
网友
1楼 · 发布于 2024-05-20 18:22:24

查看XML文档,我认为唯一重要的区别是实际的<SignatureValue>内容。虽然它在Base64序列方面是相同的,但请注意,在修改后的XML中,它包含换行符

查看XMLDSIG规范,我们发现:http://www.w3.org/TR/xmldsig-core/#sec-SignatureValue

The SignatureValue element contains the actual value of the digital signature; it is always encoded using base64 [MIME]

然后参考RFC 2045。这是链接:http://www.ietf.org/rfc/rfc2045.txt

第6.8节规定了Base64编码,其中提到:

The encoded output stream must be represented in lines of no more than 76 characters each.

这正是您在修改的XML中所做的。将XML转换为DOM,元素的文本内容将完全保留在输入文档中,包括换行符。我猜想Java XML加密包使用的Base64解码器严格遵守规范,并且无法完全解析原始XML文档中的签名

我建议在方法verify中获得XMLSignature后,尝试对其调用getSignatureValue()。这将给您一个XMLSignature.SignatureValue。尝试从中获取字节数组。如果它是空的,那么太快就切断了获取XMLSignature.SignatureValue完全失败的机会,以上可能就是问题所在

相关问题 更多 >