<p>看起来输出要求有点变化!然而,这应该提供足够的动力来消除这些粗糙的边缘。在</p>
<pre><code>dataStore = {}
# Method to process an input line
def processLine(dateStr, val):
if dateStr not in dataStore:
dataStore[dateStr] = val
else:
dataStore[dateStr] += val
# Method to read input file line by line
def doStuff(inFile, outFile):
with open(inFile, 'r') as fp:
for line in fp:
dateStr, val = line.split()
# cast decimal value to integer
val = int(val)
# process the date string to only keep the month and year
dateStr = dateStr.split('/')
dateStr = "/".join((dateStr[1], dateStr[2]))
processLine(dateStr, val)
# once you are done reading file, generate output
writeBuf = []
for key in dataStore:
writeBuf.append((key, dataStore[key]))
writeBuf.sort()
with open(outFile, 'wb') as fp:
for tup in writeBuf:
line = '01/'+tup[0]+' - 30/'+tup[0] + ' ' + str(tup[1]) + '\n'
fp.write(line)
if __name__ == '__main__':
inFile = 'data.txt'
outFile = 'result.txt'
doStuff(inFile, outFile)
</code></pre>
<p>您可以很容易地将这一天也包括在内。只需修改我处理<code>dateStr</code>的部分。<code>processLine</code>方法也会改变。在</p>
<hr/>
<p>StackOverflow<strong>不是</strong>让别人做你的全部作业。展示你当前的进展,随时寻求帮助解决错误和改进。下次你在这里寻求帮助时请记住这一点。在</p>