我有一个代码,该代码检索mbox.txt并分割From
行以获取星期几,并计算一天出现的频率。我设法做到了这一点,但现在我只能按照星期几对列表进行排序。
filename = input("Please Enter A File Name: ")
filehand = open (filename)
count=dict()
for line in filehand:
if not line.startswith('From ') : continue
line = line.split()
day = line[2]
count[day] = count.get(day,0)+1
Flist = list()
for key, value in count.items():
Flist.append((key, value))
Flist.sort(key = lambda l: (l[1], l[0]), )
for key, value in Flist:
print (key, value)
我的输出:
Please Enter A File Name: mbox.txt
Sat 61
Sun 66
Wed 292
Mon 299
Fri 315
Tue 372
Thu 392
有没有办法让它像下面的列表一样显示?
Mon 299
Tue 372
Wed 292
Thu 392
Fri 315
Sat 66
Sun 61
答案 0 :(得分:1)
代替这个:
Flist.sort(key = lambda l: (l[1], l[0]), )
尝试一下:
days = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
Flist = sorted(Flist, key= lambda l : days.index(l[0]))
# Or,
Flist.sort(key = lambda l: days.index(l[0]))
答案 1 :(得分:1)
根据建议,使用collections.OrderedDict()
:
from collections import OrderedDict
weekdays = OrderedDict({
'Mon': 0,
'Tue': 0,
'Wed': 0,
'Thu': 0,
'Fri': 0,
'Sat': 0,
'Sun': 0})
filename = input("Please Enter A File Name: ")
with open(filename) as f:
for line in f:
if line.startswith('From '):
line = line.strip().split()
weekdays[line[2]] += 1
for weekday, count in weekdays.items():
print(weekday, count)