使用python和re库读取vcf文件数据

Reading vcf file data using python and re library

这是.vcf文件数据里面的内容。

BEGIN:VCARD
VERSION:4.0
N:Muller;CCCIsabella;;;
FN:Muller
ORG:Bubba Gump Shrimp Co.
TITLE:Shrimp Man
PHOTO;MEDIATYPE=image/gif:http://www.example.com/dir_photos/my_photo.gif
TEL;TYPE=work,voice;VALUE=uri:tel:+16829185770
REV:20080424T195243Z
END:VCARD

BEGIN:VCARD
VERSION:4.0
N:Mraz;CCCEdwardo;;;
FN:Mraz
ORG:Bubba Gump Shrimp Co.
TITLE:Shrimp Man
PHOTO;MEDIATYPE=image/gif:http://www.example.com/dir_photos/my_photo.gif
TEL;TYPE=work,voice;VALUE=uri:tel:+18083155095
REV:20080424T195243Z
END:VCARD

BEGIN:VCARD
VERSION:4.0
N:Reynolds;CCCBrant;;;
FN:Reynolds
ORG:Bubba Gump Shrimp Co.
TITLE:Shrimp Man
PHOTO;MEDIATYPE=image/gif:http://www.example.com/dir_photos/my_photo.gif
TEL;TYPE=work,voice;VALUE=uri:tel:+15089473508
REV:20080424T195243Z
END:VCARD

我想要我的数据如下。

data = [{'name': 'Muller','phone': '+16829185770'}, {'name': 'Mraz', 'phone': '+18083155095'}, {'name': 'Reynolds','phone': '+15089473508'}]

但是我没有得到上面的数据。在这种情况下请帮帮我。这里我是用repython包来解决的

import re
file = open('contacts.vcf', 'r')
contacts = []
for line in file:
    name = re.findall('FN:(.*)', line)
    tel = re.findall('tel:(.*)', line)
    nm = ''.join(name)
    tel = ''.join(tel)
    if len(nm) == 0 and len(tel) == 0:
        continue
    data = {'name' : nm, 'phone' : tel}
    contacts.append(data)
print(contacts)

下面的结果名称和 phone 正在添加差异。

[{'name': 'Muller', 'phone': ''}, {'name': '', 'phone': '+16829185770'}, {'name': 'Mraz', 'phone': ''}, {'name': '', 'phone': '+18083155095'}, {'name': 'Reynolds', 'phone': ''}, {'name': '', 'phone': '+15089473508'}]

调试时经常使用 print 来找出代码出错的地方。例如,如果您在 tel = ''.join(tel) 之后插入 print(">",nm,tel),您应该得到以下输出:

>  
>  
>  
> Muller 
>  
>  
>  
>  +16829185770
>  
>  
>  
>  
>  
>  
> Mraz 
>  
[... continued...]

显然,这是因为您的 for 循环在文件中的每个 而不是每张卡片上运行(从技术上讲,您甚至承认这一点:for line in file:).

您可能有兴趣使用一个模块来解析此文件(快速 google 提出了 vobject 包),这将消除对 re 的需要。如果你有雄心壮志,你可以手动解析它(不太熟悉格式,所以这里有一个即兴的例子)。

CARDMATCHER = re.compile(r"""
^                 ## Match at Start of Line (Multiline-flag)
    BEGIN:VCARD   ## Match the string "BEGIN:VCARD" exactly
$                 ## Match the End of Line (Multiline-flag)
.*?               ## Match characters (.) any number of times(*),
                  ## as few times as possible(?), including new-line(Dotall-flag)
^                 ## Match at Start of Line (Multiline-flag)
    END:VCARD     ## Match the string "END:VCARD" exactly
$                 ## Match the End of Line (Multiline-flag)
""", re.MULTILINE|re.DOTALL|re.VERBOSE)

VALUERE = re.compile("""
^(?P<type>[A-Z]+) ## Match Capital Ascii Characters at Start of Line
(?P<sep>:|;)     ## Match a colon or a semicolon
(?P<value>.*)    ## Match all other characters remaining
""", re.VERBOSE)

class MyVCard():
    def __init__(self,cardstring):
        self.info = defaultdict(list)
        ## Iterate over the card like you were doing
        for line in cardstring.split("\n"):
            ## Split Key of line
            match = VALUERE.match(line)
            if match:
                vtype = match.group("type")
                ## Line Values are separated by semicolons
                values = match.group("value").split(";")

                ## Lines with colons appear to be unique values
                if match.group("sep") == ":":
                    ## If only a single value, we don't need the list
                    if len(values) == 1:
                        self.info[vtype] = values[0]
                    else:
                        self.info[vtype] = values

                ## Otherwise (Semicolon sep), the value may not be unique
                else:
                    ## Semicolon seps also appear to have multiple keys
                    ## So we'll use a dict
                    out = {}
                    for val in values:
                        ## Get key,value for each value
                        k,v = val.split("=",maxsplit=1)
                        out[k] = v
                    ## Make sure we havea list to append to
                    self.info[vtype].append(out)
    def get_a_number(self):
        """ Naive approach to getting the number """
        if "TEL" in self.info:
            number = self.info["TEL"][0]["VALUE"]
            numbers = re.findall("tel:(.+)",number)
            if numbers:
                return numbers[0]
        return None

def get_vcards(file):
    """ Use regex to parse VCards into dicts. """
    with open(file,'r') as f:
        finput = f.read()
    cards = CARDMATCHER.findall(finput)
    return [MyVCard(card) for card in cards]

print([{"fn":card.info['FN'], "tel":card.get_a_number()} for card in get_vcards(file)])

同样,我不对这段代码做任何保证,因为我不会查找 vcf 格式的所有规范,并且建议使用专门为此设计的模块。

您可以试试下面的代码。

import re
file = open('vcards-2.vcf', 'r')
contacts = []
phone = []
for line in file:
    name = re.findall('FN:(.*)', line)
    nm = ''.join(name)
    if len(nm) == 0:
        continue

    data = {'name' : nm.strip()}
    for lin in file:
        tel = re.findall('pref:(.*)', lin)
        tel = ''.join(tel)

        if len(tel) == 0:
            continue

        tel = tel.strip()
        tel = ''.join(e for e in tel if e.isalnum())
        data['phone'] = tel
        break
    contacts.append(data)

print(contacts)

您将得到以下结果

[{'name': 'Muller','phone': '+16829185770'}, {'name': 'Mraz', 'phone': '+18083155095'}, {'name': 'Reynolds','phone': '+15089473508'}]