0

我已经做了一个联系人管理器,我有:

def look_up_contact():
    print("-------------------------------------------------")
    choice = input("Please enter the last name of the contact you would like to view: ")
    print("-------------------------------------------------")
    person_list = Contacts[choice]
    try:
        for person in person_list:
            print("Contact: " + person.get_last_name() + ", " + person.get_first_name())
            print("Phone Number: " + person.get_phone_num())
            if type(person) == Friend:
                print("Email: " + person.get_email())
                print("Birthday: " + person.get_birth_date())

我如何修改它以查看文本文件?

我了解基础知识,但这很棘手

textcontacts = open( 'contacts.txt' )

如果在 'person' 或 txt 中找不到人员,我还想提供一些关于添加错误消息的反馈:

我尝试过尝试:方法

except Exception as ex:
    print(' Sorry, The person you are looking for could not be found ')

我正在使用 python 3.x

4

2 回答 2

1

你可以试试这个:

from collections import namedtuple


class ContactNotFoundError(Exception):
pass


def look_up_contact():
print('----------------------------------')
choice = input("Please enter the last name of the contact you would like to view: ")
print('----------------------------------')
Contact = namedtuple("Contact", "FirstName LastName PhoneNumber Email BirthDate")
with open('ListOfContacts.txt', 'r') as listOfNames:
    searchLines = listOfNames.readlines()
isFound = False
for line in searchLines:
    if choice in line:
        isFound = True
        Contact(*line.split(','))
if not isFound:
    raise ContactNotFoundError


if __name__ == '__main__':
look_up_contact()

HTH,菲尔

于 2013-08-23T21:36:11.960 回答
1

你可以用字典。也许代码会更容易阅读并且更快地访问数据(而且它更pythonic):

person_list = {}

person_list["friend1"] = {}

person_list["friend1"]["number"] = 1234567890
person_list["friend1"]["email"] = 'blabla@gmail.com'
person_list["friend1"]["friend"] = True

如果朋友在列表中,您可以通过以下方式简单地查找:

if "friend1" in person_list:
    ...
else
    ...

然后以更好的方式打印,您可以使用 PrettyPrint:

import pprint
pp = pprint.PrettyPrinter()
pp.pprint(person_list)

这是结果:

{'friend1': {'email': 'blabla@gmail.com',
             'friend': True,
             'number': 1234567890}}
于 2013-08-23T02:37:00.127 回答