Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Regular Expressions in Python Introduction to Regular Expressions Compiling and Loops

Tom Watson
Tom Watson
9,987 Points

Regex Extra Credit

Hey guys,

Here's the code I wrote for the Extra Credit to this module, if anyone has any feedback that would be great!

import re


file = open('names.txt')
data = file.read()
file.close()

expr = re.compile(r'''
    ^(?P<last_name>[-\w ]+)?,\s # Last Name
    (?P<first_name>[-\w ]+)\t  # First Name
    (?P<email>[-\w\d.+]+@[-\w\d.]+)\t  # Email
    (?P<phone>\(?\d{3}\)?-?\s?\d{3}-\d{4})?\t  # Phone
    (?P<job>[\w\s]+,\s[\w\s.]+)\t?  # Job and company
    (?P<twitter>@[\w\d]+)?$  # Twitter
''', re.M|re.X)


class Person:
    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

    def __str__(self):
        string = ''
        for k, v in self.__dict__.items():
            string += '{}: {}\n'.format(k, v)
        return string

    @classmethod
    def construct(cls, list, expr, data):
        for match in expr.finditer(data):
            list.append(cls(**match.groupdict()))


class AddressBook(list):
    def search(self, term=None):
        if term:
            result = []
            for person in self:
                for k, v in person.__dict__.items():
                    try:
                        if term in v and person not in result:
                            result.append(person)
                    except (AttributeError, TypeError):
                        continue
            return result
        return self


if __name__ == "__main__":
    address_book = AddressBook()
    Person.construct(address_book, expr, data)
    for item in address_book.search('kenneth'):
        print(item)

Hi Tom Watson -

Thanks for posting this. I was also trying to complete this extra task. I had the class constructed for each person but was struggling with the concept of adding each of them to an address book, so your example was very helpful :)

Chris