[英]Get all values for an attribute in a vcard using python vobject
If I import a vcard with vobject like this:如果我像这样导入带有 vobject 的 vcard:
with open(some_file_containing_a_vcard,
"r" , encoding="utf-8") as fd:
vcard_content = vobject.readOne(fd.read(),
ignoreUnreadable=True)
How fo I get all telephone numbers or emails, if there are more than one provides by the vcard?如果 vcard 提供多个电话号码或电子邮件,我如何获取所有电话号码或电子邮件?
I only found:我只发现:
vcard_content.tel.value
vcard_content.email.value
...but this only returns the first of each. ...但这只会返回第一个。
As I dived into the code, it seems the entities are created as clases.当我深入研究代码时,似乎实体是作为类创建的。 So a vcard's attribute "TEL" gets created as "tel".
因此,vcard 的属性“TEL”被创建为“tel”。 What, if I have a cell and a work phone number?
如果我有手机和工作电话号码怎么办?
I am totally stuck :-)我完全被困住了:-)
You can actually achieve this by using the contents
attribute, which is a dictionary. 实际上,您可以通过使用
contents
属性(它是字典)来实现此目的。 So you would access a list of all TEL properties using something like 因此,您可以使用以下方式访问所有TEL属性的列表:
with open(path_to_vcard) as f:
text = f.read()
card = vobject.readOne(text)
print card.contents['tel']
which will print the list of all TEL properties (even if there is only one or none). 它将打印所有TEL属性的列表(即使只有一个或没有)。
I solved it with the following code snippet: 我用以下代码片段解决了它:
stream = io.open(some_file_containing_a_vcard, "r", encoding="utf-8")
vcf = vobject.readComponents(stream, ignoreUnreadable=True)
for child in vcard.getChildren():
name = child.name.lower()
value = child.value
attribs = child.params.get("TYPE", [])
filtered_type = [x.lower() for x in attribs if x.lower() in (
"work", "home", "cell", "fax"
)]
if len(filtered_type) == 0:
filtered_type = ["unspec"]
# Do something with it... i.e. adding to a dict()
stream.close()
This works for me :-) 这对我有用:-)
There are attributes named tel_list
and email_list
that should provide the other entries you're looking for.有名为
tel_list
和email_list
属性应该提供您正在寻找的其他条目。
Elements in these lists act just like "tel" and "email", and each also has a .value
and .type_param
that you might want to check to disambiguate.这些列表中的元素就像“tel”和“email”一样,每个元素也有一个
.value
和.type_param
,您可能需要检查以消除歧义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.