سؤال

Code:

import re


def add_details(details_dict, file_mode):
    with open("address.txt", file_mode) as book:
        book.write("Name: {}\n".format(details_dict['Name']))
        book.write("Address: {}\n".format(details_dict['Address']))
        book.write("Home Phone No.: {}\n".format(details_dict['Home Phone No.']))
        book.write("Mobile Phone No.: {}".format(details_dict['Mobile Phone No.']))
        book.write("\n---------------\n")



def delete_person(name):
    with open("address.txt", "r+") as book:
        records = re.split("[-]+", book.read(), re.M)
        for data in records:
            record = get_record(data)
            if record.get('Name', None) != name:
                add_details(record, "w")


def get_record(string):
    return dict(re.findall("^(.*): (.*)$", string, re.M))


def print_record(record):
    print "\n"
    print "Name: {}".format(record['Name'])
    print "Address: {}".format(record['Address'])
    print "Home Phone No.: {}".format(record['Home Phone No.'])
    print "Mobile Phone No.: {}".format(record['Mobile Phone No.'])


def search_for_person(name):
    with open("address.txt", "r") as book:
        records = re.split("[-]+", book.read(), re.M)
        for data in records:
            record = get_record(data)
            if record.get('Name', None) == name:
                print_record(record)


choice = raw_input("Add a new person (1), delete a person(2), or search for a person(3)?\n")
if choice == "1":
    details = {'Name':"", 'Address':"", 'Home Phone No.':"", 'Mobile Phone No.':""}
    details['Name'] = raw_input("Enter name of contact: ")
    details['Address'] = raw_input("Enter address of contact: ")
    details['Home Phone No.'] = raw_input("Enter Home Telephone No. of contact: ")
    details['Mobile Phone No.'] = raw_input("Enter Mobile Telephone No. of contact: ")

    add_details(details, "a")

elif choice == "2":
    name = raw_input("Enter name to delete: ")
    delete_person(name)

elif choice == "3":
    name = raw_input("Enter name: ")
    print search_for_person(name)

Basically, whenever I try and delete a person, using the delete_person() method, I get this traceback:

Traceback (most recent call last):
  File "address.py", line 56, in <module>
    delete_person(name)
  File "address.py", line 19, in delete_person
    add_details(record, "w")
  File "address.py", line 6, in add_details
    book.write("Name: {}\n".format(details_dict['Name']))
KeyError: 'Name'

However, everything except that method works fine. Considering I've set the dictionaries up in the exact same way, I shouldn't be getting an error, but I am anyway. Any help on this? Here's the layout of the file, if needed:

Name: test
Address: testaddress
Home Phone No.: 2313123121233
Mobile Phone No.: 423423423432
---------------
Name: test2
Address: testaddress2
Home Phone No.: 342353454345
Mobile Phone No.: 231231391
---------------
هل كانت مفيدة؟

المحلول

You always add ------- after ever record; this leads to an empty record being read, as there is nothing but whitespace after the last such line:

>>> record='''\
... Name: test
... Address: testaddress
... Home Phone No.: 2313123121233
... Mobile Phone No.: 423423423432
... ---------------
... '''
>>> import re
>>> re.split("[-]+", record, re.M)
['Name: test\nAddress: testaddress\nHome Phone No.: 2313123121233\nMobile Phone No.: 423423423432\n', '\n']

Note the '\n' entry at the end. That leads to an empty dictionary with no 'Name' key:

>>> dict(re.findall("^(.*): (.*)$", '\n', re.M))
{}

Test for empty dictionaries:

record = get_record(data)
if record and record.get('Name', None) == name:
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top