Skip to content

Instantly share code, notes, and snippets.

@jennyonjourney
Last active October 16, 2022 12:38
Show Gist options
  • Save jennyonjourney/f71a36dfa36849378a1be9f7708e5e01 to your computer and use it in GitHub Desktop.
Save jennyonjourney/f71a36dfa36849378a1be9f7708e5e01 to your computer and use it in GitHub Desktop.
Python Data Structures (Coursera) Assignement 10.2
# 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 stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below.
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 "):
time = line.split()[5].split(":")
counts[time[0]] = counts.get(time[0], 0) + 1
list=list()
for key, value in counts.items():
list.append((key,value))
list.sort()
for hour, counts in list:
print(hour, counts)
@anishagithub
Copy link

why is my code not working:
xs=open('8.5not.txt')
c=dict()
p=list()
for line in xs:
if line.startswith('From '):
words=line.split()
else:
continue
for word in words:
m=word[5].split(':')
c[m[0]]=c.get(m[0],0)+1
for k,v in c.items():
p.append(k,v)
p.sort()
print(p)

@kapazan
Copy link

kapazan commented Oct 16, 2022

The code works but it is still problematic. If you write "From" instead of "From " without a space at the end, code blows up as it also iterates the lines whose length are smaller than 5.

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