Accessing Name, Firstname... from a VObject in Python

109 Views Asked by At

I might be very stupid here, and my knowledge about Python is nearly at 0.

I get a vcard from my Mac Contacts - I can access it and transform most of the data. Simple outputs are easy. I lack when I want to access data which is divided - I would call it an array, or dict or list...

Simple task: I want to get the first name, last name and middle name: Here is my test card:

BEGIN:VCARD
VERSION:3.0
N:Doe;John;;;
FN:John Doe
ORG:Example.com Inc.;
TITLE:Imaginary test person
EMAIL;type=INTERNET;type=WORK;type=pref:[email protected]
TEL;type=WORK;type=pref:+1 617 555 1212
TEL;type=WORK:+1 (617) 555-1234
TEL;type=CELL:+1 781 555 1212
TEL;type=HOME:+1 202 555 1212
item1.ADR;type=WORK:;;2 Enterprise Avenue;Worktown;NY;01111;USA
item1.X-ABADR:us
item2.ADR;type=HOME;type=pref:;;3 Acacia Avenue;Hoemtown;MA;02222;USA
item2.X-ABADR:us
NOTE:John Doe has a long and varied history\, being documented on more police files that anyone else. Reports of his death are alas numerous.
item3.URL;type=pref:http\://www.example/com/doe
item3.X-ABLabel:_$!<HomePage>!$_
item4.URL:http\://www.example.com/Joe/foaf.df
item4.X-ABLabel:FOAF
item5.X-ABRELATEDNAMES;type=pref:Jane Doe
item5.X-ABLabel:_$!<Friend>!$_
CATEGORIES:Work,Test group
X-ABUID:5AD380FD-B2DE-4261-BA99-DE1D1DB52FBE\:ABPerson
END:VCARD

So the field I want to get is "N" - so when I try:

vcard.n.value

I get: John Doe

vCard.n.value.family

I get: Doe

vcard.n.value.name

I get:

AttributeError: 'Name' object has no attribute 'name'

vCard.n

I get: <N{} John Doe >

So what's this structure: <N{} John Doe > ??

Could somebody give me a few hints?

I want to extract first and last name from a VCF with Vobject. But I can only get the full name (fn) or the name with some spaces.

1

There are 1 best solutions below

0
On

In vobject, values of N are structured, as you've discovered.

The attributes of interest are:

  • prefix
  • given
  • additional
  • family
  • suffix

So in the specific case you mention, you'd want

vcard.n.value.given

to get the "John" value for "John Doe".

You can discover this by using the dir() function at the interpreter prompt.

>>> import vobject
>>> vcard = vobject.newFromBehavior('vcard')
>>> n = vcard.add('n')
>>> dir(n.value)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'additional', 'family', 'given', 'prefix', 'suffix', 'toString']
>>>

The attributes with double underscore prefix/suffix are basically implementation details of the language/interpreter. The toString attribute is an internal vobject function for stringifying a list.