Parsing with Python

I’ve been given a list of contacts in vCard format of people interested in interactive storytelling. Here’s one of them.

BEGIN:VCARD
VERSION:3.0
PRODID:-//Apple Inc.//Mac OS X 10.9.1//EN
N:Maya;Bill;;;
FN:Bill Maya
EMAIL;type=INTERNET;type=WORK;type=pref:bill.maya@gmail.com
CATEGORIES:Phrontisterion,Team
UID:bcbea367-d59d-493c-8f28-5f3a524a28b2
X-ABUID:E2B6D1B2-EF7C-4C24-926A-01973C141240:ABPerson
END:VCARD

I want to send out an email to everyone in this list to tell them the Phrontisterion Online blog has been rebooted. There’s somewhere between 30-40 email address so I probably could have cut and pasted each one into a text file but why go the brute force route when when it might possible to automate it. I’ve been thinking about learning Python for a side project so I thought I’d try to use it to parse the file’s contents.

Here’s the code that opens the file and prints out every line.

fyle = open('C:\Users\billm_000\Desktop\Phrontisterion_1.txt')

for lyne in fyle:
    print lyne

fyle.close

But I’m only interested in the name and the email address. These lines are prefaced with “FN” and EMAIL” respectively. So lets just find those lines.

fyle = open('C:\Users\billm_000\Desktop\Phrontisterion_1.txt')

for lyne in fyle:
    nameId = "FN"
    if nameId in lyne:
        print lyne #2</pre>
<pre><code>emailId = &quot;EMAIL&quot;
if emailId in lyne:
    print lyne #2
</code></pre>
<pre>
fyle.close

Here’s the result.

FN:Bill Maya
EMAIL;type=INTERNET;type=WORK;type=pref:bill.maya@gmail.com

So now I just need to parse out the name and the email address from the individual lines and write those lines to a text file.

fyle = open('C:\Users\billm_000\Desktop\Phrontisterion_1.txt')
output = open('C:\Users\billm_000\Desktop\Phrontisterion_Output.txt', 'w') #4

for lyne in fyle:</pre>
<pre><code>nameId = &quot;FN&quot;
if nameId in lyne:
    print lyne[3:]
    output.write(lyne[3:]) 

emailId = &quot;EMAIL&quot;
if emailId in lyne:
    colonPosition = lyne.find(':')
    print lyne[colonPosition + 1:]
    output.write(lyne[colonPosition + 1:] + '\n')
</code></pre>
<pre>
fyle.close
output.close

Mission accomplished.

Bill Maya
bill.maya@gmail.com

It took me about 15-20 minutes to do this (less time than it took me to write this post). Of course Google was invaluable (what did developers ever do before the internet?). Here are some of the pages I used.

I definitely think Python is going to be the next new language I learn when I get the time and the right project.

Most-Popular-Coding-Languages-2014

This entry was posted in Uncategorized and tagged . Bookmark the permalink.