.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'}]
但是我没有得到如上所述的数据。在这种情况下,请帮帮我。在这里,我正在使用re python包来解决。
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)
以下结果名称和电话的添加有所不同。
[{'name': 'Muller', 'phone': ''}, {'name': '', 'phone': '+16829185770'}, {'name': 'Mraz', 'phone': ''}, {'name': '', 'phone': '+18083155095'}, {'name': 'Reynolds', 'phone': ''}, {'name': '', 'phone': '+15089473508'}]
答案 0 :(得分:0)
通常在调试时,经常在各个点使用print
来找出代码出错的地方。例如,如果您在print(">",nm,tel)
之后插入tel = ''.join(tel)
,则应获得以下输出:
>
>
>
> Muller
>
>
>
> +16829185770
>
>
>
>
>
>
> Mraz
>
[... continued...]
显然,这是因为您的for
循环正在文件中的每个行而不是每个卡上运行(从技术上讲,您甚至承认:for line in file:
)。 / p>
您可能对使用模块来解析此文件感兴趣(快速的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
格式的所有规范,因此我对这段代码不做任何保证,建议使用专门为此设计的模块。
答案 1 :(得分:0)
您可以尝试以下代码。
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'}]