【问题标题】:Get all values for an attribute in a vcard using python vobject使用 python vobject 获取 vcard 中属性的所有值
【发布时间】:2017-02-01 09:21:17
【问题描述】:

如果我像这样使用 vobject 导入 vcard:

with open(some_file_containing_a_vcard,
                  "r" , encoding="utf-8") as fd:
            vcard_content = vobject.readOne(fd.read(),
                                            ignoreUnreadable=True)

如果电子名片提供多个电话号码或电子邮件,我如何获得所有电话号码或电子邮件?

我只找到了:

vcard_content.tel.value
vcard_content.email.value

...但这只会返回每个中的第一个。

当我深入研究代码时,似乎实体是作为类创建的。因此,vcard 的属性“TEL”被创建为“tel”。如果我有手机和工作电话号码怎么办?

我完全被困住了:-)

【问题讨论】:

  • 能否提供您正在使用的电子名片?
  • 很遗憾没有。但我同时解决了它,稍后我会更新这个问题。我已经通过使用 getChildren() 并遍历 vcard 的所有行来解决它。这样我就得到了所有的信息。示例如下...
  • 太好了,很高兴你能弄明白

标签: python vcf-vcard vobject


【解决方案1】:

您实际上可以通过使用contents 属性来实现这一点,它是一个字典。因此,您可以使用类似

的方式访问所有 TEL 属性的列表
with open(path_to_vcard) as f:
    text = f.read()

card = vobject.readOne(text)
print card.contents['tel']

这将打印所有 TEL 属性的列表(即使只有一个或没有)。

【讨论】:

    【解决方案2】:

    我用下面的代码sn-p解决了:

    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()
    

    这对我有用:-)

    【讨论】:

      【解决方案3】:

      有名为 tel_listemail_list 的属性应该提供您正在寻找的其他条目。

      这些列表中的元素就像“tel”和“email”一样,每个元素还有一个.value.type_param,您可能需要检查它们以消除歧义。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-11-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-29
        • 1970-01-01
        相关资源
        最近更新 更多