簡體   English   中英

要刪除vcard聯系人重復項,比較.vcf文件中兩個vcard是否相等,這不適用於簡單的== vobject比較

[英]To remove vcard contact duplicates, comparing if two vcards are equal in .vcf file does not work with simple == vobject comparison

    #!/usr/bin/env python2.7 

    import vobject

    abfile='/foo/bar/directory/file.vcf' #ab stands for address book  

    ablist = []

    with open(abfile) as source_file:
        for vcard in vobject.readComponents(source_file):
          ablist.append(vcard)         

    print ablist[0]==ablist[1]

上面的代碼應該返回True,但這不是因為vcard即使相同也被認為是不同的。 最終目標之一是找到一種從vcard文件中刪除重復項的方法。 優點:有沒有一種使比較兼容的方法,可以使用一種快速的方法來統一Python中的列表,例如:

    set(ablist) 

刪除重復項? (例如,以某種方式將vcard轉換為字符串...)。 在上面的代碼中len(set(ablist))返回2而不是預期的1 ...

相反,如果不比較整個vcard,我們比較它的一個組成部分,如下所示:

    print ablist[0].fn==ablist[1].fn

那么我們確實會看到預期的行為並收到True作為響應...

這是測試中使用的文件內容(只有兩個相同的vcard):

    BEGIN:VCARD
    VERSION:3.0
    FN:Foo_bar1
    N:;Foo_bar1;;;
    EMAIL;TYPE=INTERNET:foobar1@foo.bar.com
    END:VCARD
    BEGIN:VCARD
    VERSION:3.0
    FN:Foo_bar1
    N:;Foo_bar1;;;
    EMAIL;TYPE=INTERNET:foobar1@foo.bar.com
    END:VCARD

@Brian Barcelona,關於您的回答,只是為了讓您知道,而不是:

ablist = []

with open(abfile) as source_file:
    for vcard in vobject.readComponents(source_file):
      ablist.append(vcard)

您可以這樣做:

with open(abfile) as source_file:
    ablist = list(vobject.readComponents(source_file))

順便說一句,我查看了該模塊的源代碼,由於vcard的不同組件可能相同但順序不同,因此不能保證您的解決方案能正常工作。 我認為最好的方法是讓您自己檢查每個相關組件。

我發現以下將起作用-洞察是對vcard進行“ serialize()”:

#!/usr/bin/env python2.7 

import vobject

abfile='/foo/bar/directory/file.vcf' #ab stands for address book  

ablist = []

with open(abfile) as source_file:
    for vcard in vobject.readComponents(source_file):
      ablist.append(vcard)         

print ablist[0].serialize()==ablist[1].serialize()

但是,應該有一個更好的方法來進行...任何幫助將受到歡迎!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM