在文本文件中“查找”

时间:2013-08-23 02:05:31

标签: python python-3.x

我已经成为联络经理,我有:

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' )

如果在“人物”中找不到人,我也想要一些关于添加错误消息的反馈。或者txt:

我尝试过try:method

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

我正在使用python 3.x

2 个答案:

答案 0 :(得分: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}}

答案 1 :(得分: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, 菲尔