python 编程 求答案!2、3两题

如题所述

第1个回答  2017-04-18
#!/usr/bin/env python
#coding=utf-8
import re
from datetime import datetime as dt, timedelta
import platform

if platform.python_version()[:1] == '2': #判断python版本是2还是3
    import sys
    reload(sys)
    sys.setdefaultencoding('utf8')

class Idcard(object):
    ''' 
    >>> m = Idcard('225122198611134730')
    >>> print(m.sex)
    男
    >>> m.birth
    '1986-11-13'
    >>> m.age
    30
    '''
    def __init__(self,idcard):
        self.idcard = idcard        
        if len(idcard) == 15:
            sex, birth = idcard[-1:], '19' + idcard[6:12]
        elif len(idcard) == 18:
            sex, birth = idcard[-2:-1], idcard[6:14]   
        else:
            raise Exception('len(idcard) is {} (15/18)'.format(len(idcard)))
        self._sex = int(sex) % 2
        self._birth = birth
    
    @property
    def sex(self):
        return u'男' if self._sex % 2 else u'女'

    @property
    def age(self):  
        now, bir = dt.now(), dt.strptime(self._birth, '%Y%m%d')
        beforebirth = (now - dt(now.year, bir.month, bir.day)).days < 0
        return dt.now().year - int(self._birth[:4]) - beforebirth

    @property
    def birth(self):
        return dt.strptime(self._birth, '%Y%m%d').strftime('%Y-%m-%d')

def alignment(str1, space, align = 'left'):
    length = len(str1.encode('gb2312'))
    space = space - length if space >=length else 0
    if align == 'left':
        str1 = str1 + ' ' * space
    elif align == 'right':
        str1 = ' '* space +str1
    elif align == 'center':
        str1 = ' ' * (space //2) +str1 + ' '* (space - space // 2)
    return str1
    
def main():
    fname = 'customer.txt'
    '''
    with open(fname, 'w') as f:
        f.write("""
        郑文杰 225122198611134730
        文萍 225122198912094740
        郑妈妈  225122590303476
        郑爸爸 225122560506471
        """)
    '''    
    newf = 'ourcustomers.txt'
    with open(fname) as f:
        s = f.readlines()
    L, newL = [re.split(r'\s+', i.strip()) for i in s], []
    for i in L:
        if len(i) == 2:
            g = Idcard(i[1])
            newL.append('{}{}{}'.format(
                alignment(i[0], 10), alignment(g.sex, 8), g.age))
    with open(newf, 'w') as f:
        f.write('\n'.join(newL))
    print('\n'.join(newL[:100]))
    print('Customer data has been write into {}'.format(newf))

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    main()

第2个回答  2017-04-18
#-*- coding:utf-8 -*-
import time
import datetime
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

def msg():
   f = open('test.txt','r')
   '''
       李丽丽  320382199606160123
       徐华彩  320382199606160134
       蔺小虎  320382199606160145
       葛俊  320382199606160156
   '''
   res = f.readlines()
   for i in range(len(res)):
       result = res[i].replace(' ', '').replace('\t', '').replace('\n', '').replace('\r', '')
       name = result[0:-18]
       num = result[-2:-1]
       now_time = datetime.datetime.now()
       time = datetime.datetime.now().strftime('%Y%m%d')
       year = result[-12:-4]
       age = int(time[0:4]) - int(year[0:4])
       if int(time[4:]) > int(year[4:]):
           age = age
       else:
           age = age - 1
       if int(num) % 2 == 0:
           sex = "女".decode('utf-8').encode('gbk')
       else:
           sex = "男".decode('utf-8').encode('gbk')
       with open('oeder.txt', 'a') as f:
           f.write(str(name) + '    ' + str(sex) + '    ' + str(age) + '\n')
       f.close()
   f.close

if __name__ == "__main__":
   start = time.clock()
   msg = msg()
   end = time.clock()
   print u'保存完成,共耗时:'+str(end - start)

追问

十分感谢

本回答被提问者采纳
第3个回答  2017-04-17
这要写多少代码啊?分太少了。追问

如果满意的话再加30分