Skip to content

Instantly share code, notes, and snippets.

@fyears
Created December 17, 2012 14:48
Show Gist options
  • Save fyears/4318816 to your computer and use it in GitHub Desktop.
Save fyears/4318816 to your computer and use it in GitHub Desktop.
add pinyin field to the contacts vcard

contacts.vcf 加上拼音字段

首先导出 contacts.vcf。 推荐使用免费工具 iTools,其实这个 gist 就是在它的格式下研究得到的。

格式如同 gist 里面的 contacts.vcf 所示。

注意 QQ 同步助手里面导出的格式很奇怪,与这个 gist 不兼容。

然后你懂的:

pip install xpinyin
cat contacts.vcf | python contacts_add_pinyin.py > result.vcf

导入 result.vcf

如果导出的工具不是很符合这个 gist 里面给出的格式,请自行研究......

提示:py 文件中第 3840,4852, 54~57 行对应的格式处理内容应该要相应修改。

BEGIN:VCARD
VERSION:3.0
N;LANGUAGE=zh-cn;CHARSET=UTF-8:张;三;;;
END:VCARD
BEGIN:VCARD
VERSION:3.0
N;LANGUAGE=zh-cn;CHARSET=UTF-8:李;四;;;
X-FIRSTPHONETIC;CHARSET=UTF-8:SI
X-LASTPHONETIC;CHARSET=UTF-8:LI
END:VCARD
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
usage:
cat contacts.vcf | python contacts_add_pinyin.py > result.vcf
'''
import sys
from xpinyin import Pinyin
def read_in():
'''
return an array of string of lines
'''
lines = sys.stdin.readlines()
for i in range(len(lines)):
lines[i] = lines[i].replace('\n','').replace('\r','')
#print lines
return lines
def split_into_person_list(lines):
single_person_list = []
all_people_list = []
for i in range(len(lines)):
if lines[i] == 'BEGIN:VCARD':
while lines[i] != 'END:VCARD':
single_person_list.append(lines[i])
i = i + 1
single_person_list.append('END:VCARD')
all_people_list.append(single_person_list)
single_person_list = []
return all_people_list
def add_pinyin_placeholder(
all_people_list,
lnpy='X-LASTPHONETIC;CHARSET=UTF-8:',
fnpy='X-FIRSTPHONETIC;CHARSET=UTF-8:',
file_coding='utf-8'
):
p = Pinyin()
for person in all_people_list:
last_name_cn = ''
first_name_cn = ''
is_in = 0
for item in person:
if item.split(';')[0] == lnpy.split(';')[0]:
is_in = 1
if item.split(';')[0] == 'N':
last_name_cn = item.split(';')[2].split(':')[1]
first_name_cn = item.split(';')[3]
if is_in == 0:
last_name_pinyin = p.get_pinyin(last_name_cn.decode(file_coding)).upper()
first_name_pinyin = p.get_pinyin(first_name_cn.decode(file_coding)).upper()
person.insert(-1,'%s%s' % (lnpy, last_name_pinyin))
person.insert(-1,'%s%s' % (fnpy, first_name_pinyin))
return all_people_list
def main():
lines = read_in()
all_people_list = split_into_person_list(lines)
result = add_pinyin_placeholder(all_people_list)
for person in result:
for item in person:
print item
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment