class Phone_book: #Please note that this line of code has no indentation, all other lines has at least one indentation.

    def __init__(self):
        self.phoneDic = {}
        commandsDic = { "add" : self.add , "lookup" : self.lookup , "alias" : self.alias,
                        "change" : self.change , "save" : self.save,
                        "load" : self.load , "quit" : self.i_quit }

        while True:
            a = input("Phone book")
            b = a.split() #Splits a line of text into list items
            try:
                commandsDic[b[0]](*b[1:]) #Allocates
            except TypeError:
                print("This function does not work")
            except KeyError:
                print("You have written an incorrect amount of arguments")
            except SystemExit:
                print("Exiting...")
                break

    def add(self, allonym, digit):
        print("Name:", allonym, "\nNumber", digit, "\nSaved in phone book!")
        self.phoneDic[digit] = [allonym]


    def encounter(self, allonym):
        found = 0
        phno = 0
        for digit, allonyms in self.phoneDic.items():
            if allonym in allonyms:
                phno = digit
                found += 1
            if found == 0:
                return 0
            elif found == 1:
                return phno
            else:
                return -1

     def alias(self, allonym, newallonym):
        if newallonym:
            phno = self.encounter(allonym)
            if phno > 0:
                self.phoneDic[phno].append(newallonym)
                print("Alias stated")


函数alias的目的是为别名本身创建一个昵称,并与该别名一起保存在内存中。我收到TypeError时无法正常工作。一个人如何减轻错误并使别名得到保存并与全名配对?

执行

输入:
电话簿添加Bromley.Jones 12345
输出:
姓名:布罗姆利·琼斯
数12345
保存在电话簿中!
输入:
电话簿别名Bromley.Jones BJ
输出:
此功能不起作用。


Allonym具有与name相同的语言定义。
全名与名称具有相同的语言定义。

最佳答案

有两个问题。首先,在encounter中:它将始终返回0,除非您要搜索的项是第一个项,因为if块位于for内。找到后,您可以简单地将其返回:

def encounter(self, allonym):
    for digit, allonyms in self.phoneDic.items():
        if allonym in allonyms:
            return digit
    return 0


但是,这里的一个问题与第二个问题有关:字典中的键是字符串,但是您将其视为整数。我将更改上面的函数以在找不到时返回None。然后在alias函数中:

def encounter(self, allonym):
    for digit, allonyms in self.phoneDic.items():
        if allonym in allonyms:
            return digit
    return None

def alias(self, allonym, newallonym):
    if newallonym:
        phno = self.encounter(allonym)
        if phno:
            self.phoneDic[phno].append(newallonym)
            print("Alias stated")

10-06 06:30