Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialTom Watson
9,987 PointsRegex 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)
1 Answer
Chris Guy
Python Web Development Techdegree Graduate 14,615 PointsHi 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