Skip to content

Instantly share code, notes, and snippets.

@zhenalexfan
Created September 3, 2019 07:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save zhenalexfan/e21b099b9271e921568132ea65268f10 to your computer and use it in GitHub Desktop.
Save zhenalexfan/e21b099b9271e921568132ea65268f10 to your computer and use it in GitHub Desktop.
Batch add phonetic names to your Chinese contacts
import csv
from pypinyin import pinyin, lazy_pinyin, Style
def cn_char(text):
return all('\u4e00' <= char <= '\u9fff' for char in text)
if __name__ == '__main__':
data =[]
with open('contacts.csv', encoding='utf-8') as f:
r = csv.reader(f, delimiter=',')
for person in r:
data.append(person)
for person in data:
first_name = person[1]
last_name = person[3]
if cn_char(first_name):
phonetic_first = lazy_pinyin(first_name)
phonetic_last = lazy_pinyin(last_name)
person[5] = ''.join(phonetic_first).title()
person[7] = ''.join(phonetic_last).title()
print(person)
with open('contacts_with_pinyin.csv', mode='w', encoding='utf-8') as f:
w = csv.writer(f, delimiter=',')
for person in data:
w.writerow(person)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment