用python实现
#!/usr/bin/python
menu = ''' Address Book menu
q - Quit
a - Add a new person
l - List all of the people in the address book
f - Find all matches to a serach string eatered by the user
r - Read previously saved data from disk
w - Write the current contents to disk'''
print menu
people = [] # list
while(True):
input = raw_input("Enter operation : ").strip()
if input == 'q':
break
elif input == 'a':
print "Adding a new person"
given_name = raw_input("Enter Given Name : ").strip()
family_name = raw_input("Enter Family Name : ").strip()
phone = raw_input("Enter Phone Number : ").strip()
mail = raw_input("Enter E-mail Address : ").strip()
if not given_name:
print "Not a valid name"
break
new_person = {
'given_name' : given_name,
'family_name' : family_name,
'phone' : phone,
'mail' : mail
}
people.append(new_person)
elif input == 'l':
#print d
for person in people:
print "{} {}, email {}, phone {}\n".format(person['given_name'],
person['family_name'],
person['phone'],
person['mail'])
elif input == 'f':
look_for = raw_input("Enter keyword to search for : ").strip()
for person in people:
if (look_for in person['given_name'] or
look_for in person['family_name'] or
look_for in person['mail']):
print "{} {}, email {}, phone {}\n".format(person['given_name'],
person['family_name'],
person['phone'],
person['mail'])
elif input == 'r':
print "Reading previously saved data from disk"
for line in open('address.txt', 'Ur'):
given_name,family_name,phone,mail = line.split()
new_person = {'given_name' : given_name,
'family_name': family_name,
'phone' : phone,
'mail' : mail}
people.append(new_person)
elif input == 'w':
print "Writing the current contents to disk"
with open('address.txt', 'w') as f:
for person in people:
f.write('{}\t{}\t{}\t{}\n'.format(person['given_name'],
person['family_name'],
person['phone'],
person['mail']))
f.close()