Last active
October 16, 2022 12:38
-
-
Save jennyonjourney/f71a36dfa36849378a1be9f7708e5e01 to your computer and use it in GitHub Desktop.
Python Data Structures (Coursera) Assignement 10.2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 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) |
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
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)