Skip to content

Instantly share code, notes, and snippets.

@najmam
Last active August 20, 2023 18:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save najmam/50a012c4a9e57e37a2fe2c72b9384107 to your computer and use it in GitHub Desktop.
Save najmam/50a012c4a9e57e37a2fe2c72b9384107 to your computer and use it in GitHub Desktop.
Convert vCard to CSV (2021-06-31)
# -*- coding: utf-8 -*-
import vobject
import re
import sys
# TODO gérer les entrées qui contiennent plus d'un numéro de téléphone, ou au moins écrire un warning
vcf = "".join(open(sys.argv[1]).readlines()).strip()
vcfs = [e for e in vcf.split("END:VCARD") if e != ""]
vcfs = [e+"END:VCARD" for e in vcfs]
contacts = []
for i,s in enumerate(vcfs):
try:
contacts.append(vobject.readOne(s))
except Exception as e:
print("error when parsing #%d" % (i+1))
print(s)
raise e
def transform_name(n):
return re.sub(re.compile("\\s+"), " ", n).strip()
def transform_tel(t):
if len(t) < 5:
return t
r = t.replace("-", "")
if r.startswith("00"): # numéro avec indicatif
return "+"+r[2:]
elif r.startswith("+"): # numéro avec indicatif
return r
return "+33"+r[1:] # numéro français
def dot_every_two_digits(ds):
return ".".join([a+b for a, b in zip(ds[::2], ds[1::2])])
def pretty_phone(t):
for ind in ["+33", "+213"]:
if t.startswith(ind):
return "{} (0){}.{}".format(ind, t[len(ind)], dot_every_two_digits(t[len(ind)+1:]))
return t
#if t.startswith("+33"):
# return "+33 (0)" + t[3] + "." + dot_every_two_digits(t[4:])
#elif t.startswith("+213"):
# return "+213 (0)" + t[4] + "." + dot_every_two_digits(t[5:])
#return t
print("phone;phone_pretty;name")
for c in contacts:
name = transform_name(str(c.n.value))
tel = transform_tel(str(c.tel.value)) if "tel" in c.contents.keys() else ""
if len(tel) > 0 and len(tel) < 5: # oublie les services type "messagerie", "info conso" etc
continue
rtel = pretty_phone(tel)
print("{};{};{}".format(tel, rtel, name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment