Skip to content

Instantly share code, notes, and snippets.

@ayubmetah
Created December 23, 2020 22:28
Show Gist options
  • Save ayubmetah/c27e9ec838b33eca63c4598fc17a2a5e to your computer and use it in GitHub Desktop.
Save ayubmetah/c27e9ec838b33eca63c4598fc17a2a5e to your computer and use it in GitHub Desktop.
What is wrong with the code for the following question?
# Open the file mbox-short.txt and read it line by line. When you find a line that starts with 'From ' like the following line:
# From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008
# You will parse the From line using split() and print out the second word in the line (i.e. the entire address of the person who sent the message). Then print out a count at the end.
# Hint: make sure not to include the lines that start with 'From:'. Also look at the last line of the sample output to see how to print the count.
# You can download the sample data at http://www.py4e.com/code3/mbox-short.txt
#MY SOLUTION
fh = open(fname)
join = list()
for line in fh:
if not line.startswith("From:") : continue
lines = line[5:].rstrip()
#print(lines)
liner = lines.split()
for word in liner:
if word in join: continue
join.append(lines)
#print(join)
for w in join:
print(w)
x = len(join)
print('There were '+ str(x) +' lines in the file with From as the first word')
#Returns
# Enter file name: mbox-short.txt
# stephen.marquard@uct.ac.za
# louis@media.berkeley.edu
# zqian@umich.edu
# rjlowe@iupui.edu
# zqian@umich.edu
# rjlowe@iupui.edu
# cwen@iupui.edu
# cwen@iupui.edu
# gsilver@umich.edu
# gsilver@umich.edu
# zqian@umich.edu
# gsilver@umich.edu
# wagnermr@iupui.edu
# zqian@umich.edu
# antranig@caret.cam.ac.uk
# gopal.ramasammycook@gmail.com
# david.horwitz@uct.ac.za
# david.horwitz@uct.ac.za
# david.horwitz@uct.ac.za
# david.horwitz@uct.ac.za
# stephen.marquard@uct.ac.za
# louis@media.berkeley.edu
# louis@media.berkeley.edu
# ray@media.berkeley.edu
# cwen@iupui.edu
# cwen@iupui.edu
# cwen@iupui.edu
# There were 27 lines in the file with From as the first word
@ayubmetah
Copy link
Author

Correction:

fname = input("Enter file name: ")
fh = open(fname)
count = 0
if len(fname) < 1:
    print("There is no file matching that name")
else:
    fh = open(fname)
    for line in fh:
        line = line.strip()
        if not line.startswith("From "): continue
        words = line.split()
        count = count +1
        print(words[1])
    print("There were", count, "lines in the file with From as the first word")

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