#!/usr/bin/env python
# coding: utf-8
import csv
with open('contacts.csv', 'r') as f:
l = csv.DictReader(f)
contacts = list(l)
keys = contacts[0].keys()
def get_key(s):
return filter(lambda x: x and s in x.lower(), keys)[0]
first_name_k = get_key('first name')
middle_name_k = get_key('middle name')
last_name_k = get_key('last name')
name_keys = [first_name_k, middle_name_k, last_name_k]
print name_keys
gap = ' ' * 4
head_line = ' 姓{} | 名{} | Middle Name'.format(gap, gap)
fill_length = len(gap) + 2
body_line_tpl = ' {last_name} | {first_name} | {middle_name}'
def cal_len(s):
u = s.decode('utf8')
length = 0
for i in u:
c = i.encode('utf8')
if len(c) > 1:
length += 2
else:
length += 1
return length
file_encoding = 'cp936'
def to_utf8(s):
if isinstance(s, unicode):
return s.encode('utf8')
if isinstance(s, str):
return s.decode(file_encoding).encode('utf8')
return str(s)
def format_name(name):
name = to_utf8(name)
length = cal_len(name)
if length >= fill_length:
return name
return name + ((fill_length - length) * ' ')
def print_names(c):
print body_line_tpl.format(
last_name=format_name(c[last_name_k]),
first_name=format_name(c[first_name_k]),
middle_name=format_name(c[middle_name_k]),
)
def has_names(c):
return c[first_name_k].strip() + c[last_name_k].strip() + c[middle_name_k].strip()
print head_line
for i in contacts:
if has_names(i):
print_names(i)