Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

I just started learning Python, and have been trying to do some practice problem

ID: 3864847 • Letter: I

Question

I just started learning Python, and have been trying to do some practice problems & examples, but I've been having some difficulty. The following is an example practice problem that I could use some help creating the code for. I'm not sure if I need to pull information from a separate (mbox-short.txt) file that I need to save. Any additional information, such as step-by-step instruction would also be greatly appreciated.

Write a program to read through the mailbox data and when youfind line that starts with “From”, you will split the line into wordsusing the split function. We are interested in who sent the message which is the second word on the From line.
Example: From stephen.marquard@uct.ac.za Sat Jan 5 09:14:162008

The program should have the follow functionalities:

1. Program should prompt the user to enter for a file name (mbox-short.txt)

2. Program also find line that starts with “From”

3. Program splits the line into words using the split function (For example, “From” “stephen.marquard@uct.ac.za” “Sat”“Jan 5 09:14:16 2008” )

4. Count the number of “From”s

5. Program figures out who sent the message, which is email address, and extracts the email address.

6. Print out all email addresses and a count at the end


This is a sample output with a few lines removed:
Enter a file name: mbox-short.txtstephen.marquard@uct.ac.zalouis@media.berkeley.eduzqian@umich.edu[...some output removed...]
ray@media.berkeley.edu

Explanation / Answer

#Breaking up the problem statement into a series of steps is good programming practice
# creating a main method
def main():

#Part - 1.
#ask user input
file_name = raw_input('Enter a File Name');
#creates a file object (not sure if by filename it meant with or without extension, modify accordingly)
f = open(file_name+".txt");
  
count = 0;
splitted_line = []
  
#Part - 2.
#readlines() => read all the lines from a file in a file object
for line in f.readlines():
# remove the after each line
line = line.strip();
if line.startswith('From'):
#Part - 3.
splitted_line.append(line.split(" "));
#Part - 4.
count+=1;
  
# iterate through all the lines starting with 'From' and print the email which is the second word in each line
#Part - 5.
for filtered_line in splitted_line:
print( filtered_line[1]);
  
# This will print the total number of lines begining with 'From'   
print(count);
  

# this will run your main method and executing this file
if __name__== "__main__":
main()