美文网首页自动化学习-python
2018-10-22:格式化内容

2018-10-22:格式化内容

作者: 种树在此时 | 来源:发表于2018-10-31 00:08 被阅读0次

    def putinfotodict(infile):
    outstr = {}
    with open(infile) as inf:
    for one in inf.read().split(',\n'):
    stuid = one.split(',')[-1]
    stuid = stuid[:-1]
    claid = one.split(',')[-2]
    atttime1 = one.split(',')[-3]
    atttime = atttime1[1:]
    valueandvalue = {}
    valueandvalue['lessonid'] = claid
    valueandvalue['checkintime'] = atttime

            if stuid not in outstr:
                outstr[stuid] = []
            outstr[stuid].append(valueandvalue)
    
        return outstr
    

    infile = 'file2.txt'
    p=putinfotodict(infile)

    print(p)

    import pprint
    pprint.pprint(p)

    '''

    標準答案

    def putinfotodict(filename):
    redic={}
    with open(filename) as f:
    lines=f.read().splitlines()
    for line in lines:
    # remove '('and ')'
    line=line.replace('(','').replace(')','').replace(';','').strip()
    parts=line.split(',')
    citime=parts[0].strip().replace("'",'')
    lessonid=int(parts[1].strip())
    userid=int(parts[2].strip())
    toadd={'lessonid':lessonid,'checkintime':citime}
    #if not in,need to create list first
    if userid not in redic:
    redic[userid]=[]
    redic[userid].append(toadd)
    #or just
    ## redic.setdefault(userid,[]).append(toadd)
    return redic

    infile = 'file2.txt'
    p=putinfotodict(infile)

    import pprint
    pprint.pprint(p)

    '''

    相关文章

      网友评论

        本文标题:2018-10-22:格式化内容

        本文链接:https://www.haomeiwen.com/subject/nwqotqtx.html