Skip to content

Instantly share code, notes, and snippets.

@zcakzwa
Created July 5, 2016 12:43
Show Gist options
  • Save zcakzwa/2bf34f782db0c43847250b5fa86bc2bf to your computer and use it in GitHub Desktop.
Save zcakzwa/2bf34f782db0c43847250b5fa86bc2bf to your computer and use it in GitHub Desktop.
10.2 Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From [email protected] Sat Jan 5 09:14:16 2008 Once you have accumulated the c…
name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
d=dict()
for line in handle:
if not line.startswith("From "):
continue
else:
line=line.split()
line=line[5]
line=line[0:2]
d[line]=d.get(line,0)+1
lst=list()
for value,count in d.items():
lst.append((value,count))
lst.sort()
for value,count in lst:
print value,count
@lazurs1
Copy link

lazurs1 commented Aug 22, 2022

fname = input("Enter file name: ") fh = open(fname) counts = dict() for line in fh: if not line.startswith('From '): continue #to skip the rest else: line = line.strip().split() #turns the line to a list

    time = line[5].split(':')
   
    hour = time[0]

#creates a dictionary and gets how often a particular hour appears if hour not in counts: counts[hour] = 1 else: counts[hour] = counts[hour] + 1

#sorts the hour in ascending order for hr,t in sorted(counts.items()): print(hr,t)

Can you please try running your code again- I ran it and get errors (I've also ran it for many many other people's code to see what it would do):

image

@faranakR
Copy link

name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
dic = {}
for line in handle:
line = line.rstrip().split()
if "From" in line:
key = line[5]
key = key.split()
for element in key:
hr = element[0:2]
if hr not in dic:
dic[hr] = 1
else:
dic[hr] += 1
lst = list()
for key, value in dic.items():
lst.append((key, value))

lst.sort()

for key, value in lst:
print(key, value)

@WestonSpiro
Copy link

name = input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
d=dict()
for line in handle:
if not line.startswith("From "):
continue
else:
line=line.split()
line=line[5]
line=line[0:2]
d[line]=d.get(line,0)+1

lst=list()
for value,count in d.items():
lst.append((value,count))

lst.sort()
for value,count in lst:
print (value,count)

@rishabhrathore055
Copy link

name = input("Enter file:")
counts = dict()
if len(name) < 1:
    name = "mbox-short.txt"
handle = open(name)
for line in handle:
    if line.startswith('From '):
        line = line.split()[5][:2]
        counts[line] = counts.get(line,0) + 1
lst = list()
for hours,count in counts.items():
    lst.append((hours,count))
    lst = sorted(lst)
for (hours,count) in lst:
    print(hours,count)

@toludoyin
Copy link

toludoyin commented Oct 21, 2022

if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
dic = dict()
for line in handle:
    if "From:" in line:
        continue
    if "From" in line:
        word_split = line.split()
        hour = word_split[5].split(":")[0]
        dic[hour] = dic.get(hour, 0)+1

lst = list()
for key, value in dic.items():
    lst.append([key, value])
lst = sorted(lst, reverse= True)

for key, value in sorted(lst):
    print(key, value)```

@ShepardDog
Copy link

name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
time = []
dictionary = {}
for line in handle:
if line.startswith("From"):
line = line.rstrip().split(":")
if len(line) > 2:
mail = line[0]
mail = mail.split()
#time.append(int(mail[-1]))
time.append(mail[-1])
#print (time)
for t in time:
if t not in dictionary:
dictionary[t] = 1
else:
dictionary[t] = dictionary[t] +1
#print (dictionary)
sortedDict = sorted(dictionary)
#print (sortedDict)
for i in sortedDict:
print (i, dictionary[i])

@amankrs21
Copy link

Mine 💯
image

@usmantariq87
Copy link

name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)

diccount={}
hislist= []

for line in handle:
words = line.split()

if len(words) > 2 and words[0] == 'From':
hr = words[5].split(':')
diccount[hr[0]] = diccount.get(hr[0], 0) + 1
else:
continue

for k,v in sorted(diccount.items()):
print(k,v)

@zykaj
Copy link

zykaj commented Jan 7, 2023

name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)

diccount={}
hislist= []

for line in handle:
words = line.split()

if len(words) > 2 and words[0] == 'From':
    hr = words[5].split(':')
    diccount[hr[0]] = diccount.get(hr[0], 0) + 1
else:
    continue

for k,v in sorted(diccount.items()):
print(k,v)

@Rea-mogetse
Copy link

ex_10_2 fname = input("Enter file name :") try: fhand=open(fname) except: print("the file does not exists") file_dict={} for line in fhand : line=line.rstrip() if line.startswith("From ") : words=line.split() time=words[5] hour=time[:2] file_dict[hour]=file_dict.get(hour,0)+1 for k,v in sorted (file_dict.items()) : print(k,v)

returns an out of range index at line 10

@Hughesjosh13
Copy link

The issue I am having is that the my code is printing out the hour every time still with the count. The count part is correct but how do I get it to only show the hour once?

Code below:
name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)
lst = list()
time_count = dict()
for line in handle:
line = line.rstrip()
if not line.startswith('From '):
continue
words = line.split()
time = words[5]
time_split = time.split(':')
hours = time_split[0]
#print(hours)
time_count[hours] = time_count.get(hours,0)+1
#print(time_count)
for k in time_count.items():
lst.append(k)
t = sorted(lst)
for k,v in t:
print(k,v)

@ali6406
Copy link

ali6406 commented Mar 17, 2023

name = input("Enter file:")
if len(name) < 1 :
name = "mbox-short.txt"
handle = open(name)

counts = dict()
for line in handle :
if line.startswith('From ') :
nums = line.split()
num = nums[5]
hrs = num[0:2]
counts[hrs] = counts.get(hrs,0) + 1

    lst = list()

for value , count in counts.items():
lst.append((value,count))
lst.sort()
for value , count in lst:
print (value,count)

@KarenTheEarth
Copy link

Screenshot 2023-04-09 at 10 25 44 pm

@ShuckZ77
Copy link

ShuckZ77 commented Apr 17, 2023

name = input("Enter file:")

handle = open(name) #mbox-short.txt

list1=list()

for lines in handle:

if lines.startswith('From '):
    
    lines2=lines.strip()
    
    lines3=lines2.split()
    
    lines4=lines3[5]
    
    lines5=lines4.split(':')
    
    lines6=lines5[0]
    
    #print(lines6)
    
    list1.append(lines6)

#print(list1)

dict1=dict()

for hrs in list1:

    dict1[hrs]=dict1.get(hrs,0)+1

#print(dict1)

for K,V in sorted(dict1.items()):
print(K,V)

@ShivaniJM
Copy link

Please help me with the code, however I correct the code I'm getting the #error
Error code

@Le12vi
Copy link

Le12vi commented May 7, 2023

Hey did you solve the issue? I am also facing the same problem

@ShivaniJM
Copy link

Yes I solved the problem.
Just leave space after 'm' in 'From '

@ChernetAsmamaw
Copy link

`name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)

email = dict()
for line in handle:
if not line.startswith('From '): continue
time = line.split()
hour = time[5].split(':')[0]
email[hour] = email.get(hour,0) +1

lst = list()
for k,v in email.items():
lst.append([k,v])
lst = sorted(lst)

for k,v in lst:
print(k,v)
`

@Le12vi
Copy link

Le12vi commented May 8, 2023

@ChernetAsmamaw i used the code you provided but still it says list index out of range.

@ChernetAsmamaw
Copy link

@Le12vi A "list index out of range" error occurs when you try to access an index of a list that does not exist. Perhaps you made a mistake when naming your list variables, could you check that?

@Joy3Luo
Copy link

Joy3Luo commented Jun 22, 2023

handle = open('mbox-short.txt')

di = dict()
for line in handle:
words = line.split()
if len(words) > 3 and words[0] == 'From':
words = line.split()
time = words[5].split(':')
hour = time[0]
di[hour] = di.get(hour,0)+1

for k, v in sorted(di.items()):
print(k,v)

@mittelwertjoe
Copy link

fname = input('Enter file name: ')
try:
fh = open(fname)
except:
print('File cannot be opened', fname)
quit()

count, hours = {}, [] #set dictionary and list

for line in fh:
if line.startswith('From '): #find lines that start with "From"
words = line.split() #splits lines into 'words'
hour = words[5][0:2] #pinpoints the time in the line and further splits to show only hour
count[hour] = count.get(hour, 0) + 1 #counts how many times that hour shows up

for k, v in count.items(): hours.append((k, v))
hours.sort() #sorts dictionary by key
for k, v in hours: print(k, v) #prints the hour, and how often that hour showed up

@Studio46000
Copy link

handle = open("mbox-short.txt")
count = dict()
for line in handle:
word = line.split()
#guardian pattern
if len (word) <1:
continue
if word[0] != 'From':
continue
word = word[5]
word = word[0:2]
count[word]=count.get(word,0)+1

t = sorted([(k,v) for k,v in count.items()])

for k,v in t:
print (k,v)

@amber020323
Copy link

name = input("Enter file:")
if len(name) < 1:
name = "mbox-short.txt"
handle = open(name)

for line in handle:
if not line.startswith('From'):
continue
else:
line = line.split()
word = line[5]
word = word.split(':')
word = word[0]
counts = dict()
for count in word:
counts[count] = counts.get( count, 0) +1
lst = list()
for k,v in counts.items():
lst.append(v,k)
lst = sorted(lst, reverse=True)

for v,k in lst:
print(k,v)

My code can not do well, can anyone find some problems? thankyou!!!

@theoriginalkamdia
Copy link

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
d=dict()
for line in handle:
if not line.startswith("From "):
continue
else:
line=line.split()
line=line[5]
line=line[0:2]
d[line]=d.get(line,0)+1

lst=list()
for value,count in d.items():
lst.append((value,count))

lst.sort()
for value,count in lst:
print(value,count)

@maulya230
Copy link

name = raw_input("Enter file:")
if len(name) < 1 : name = "mbox-short.txt"
handle = open(name)
d=dict()
for line in handle:
if not line.startswith("From "):
continue
else:
line=line.split()
line=line[5]
line=line[0:2]
d[line]=d.get(line,0)+1

lst=list()
for value,count in d.items():
lst.append((value,count))

lst.sort()
for value,count in lst:
print (value,count)

@Bonllu
Copy link

Bonllu commented Jan 12, 2024

Hi, here's mine

Captura de pantalla horario mail

@rodrigo-calle
Copy link

name = input("Enter file:")
if len(name) < 1:
    name = "mbox-short.txt"
handle = open(name)

hour_list = list() 
hour_dictionary = dict()

for line in handle:
    line_splited = line.split(" ")
    if line_splited[0] == "From":
        hour_list.append(line_splited[6][0:2])

for hour in sorted(hour_list):
    if hour_dictionary.get(hour, False) == False:
        hour_dictionary[hour] = 1
    else:
        hour_dictionary[hour] = hour_dictionary[hour] + 1

for key, value in hour_dictionary.items():
    print(key, value)

@Inspire2023
Copy link

name = input("Enter file:")
if len(name) < 1:
    name = "mbox-short.txt"
handle = open(name,'r')

counts = dict()

for line in handle: 
    if line.startswith("From "):
        pos = line.find(":")
        time = (line[pos-2 : pos]) #finding hour
        counts[time] = counts.get(time,0) + 1 #creating dictionary

order = sorted(counts.items())
for key, value in order : print(key, value)

    

@AmmadJavaid006
Copy link

Hey guys this is my code on the Q it works nicely but if there is anything that I did wrong or I could have initially avoided pls let me know :)

fname = input("Enter File Name: ")
fhandle = open(fname)
lst = list()
count = dict()
finallist = list()
for line in fhandle:
if line.startswith("From") and not line.startswith("From:"):
line = line.split()
lst.append(line[5])

for hour in lst:
hour = hour.split(":")
finallist.append(hour[0])

for ftime in finallist:
count[ftime] = count.get(ftime, 0) + 1

for x, y in sorted(count.items()):
print(x, y)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment