自动化学习-python

2018-10-22:格式化内容

2018-10-31  本文已影响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)

'''

上一篇 下一篇

猜你喜欢

热点阅读