Advertisement
Guest User

Untitled

a guest
Oct 15th, 2019
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.23 KB | None | 0 0
  1. import sys
  2.  
  3. # Exercise G
  4.  
  5. # Use the sys argv to get the argument from the command line and store it
  6.  
  7. filepath = sys.argv[1]
  8.  
  9. #print filepath
  10.  
  11. # Define a function that opens the given file and counts the words
  12.  
  13. def open_file(filepath):
  14.  
  15.     # open the file and read its contents into a variable
  16.     with open(filepath, "r") as my_file:
  17.         contents = my_file.read()
  18.    
  19.     #print contents
  20.    
  21.     # We need to loop over each word in the content string.
  22.     # Convert the string into a list of words
  23.    
  24.     # For each word in the list of words we need to have a place to store how often we've seen it.
  25.     # We want to define a data structure (dictionary?) before the loop that makes it easy to store a word and how often it's been see.
  26.    
  27.     # Make an empty dictionary to store our words  
  28.     result = {}
  29.    
  30.     # FOR LOOP
  31.     # For each word in the list, check if we've seen it already. Similar to last week...
  32.     # If we have seen it we can add 1 to that count
  33.     # If we haven't seen it we can se the count to 1 as it's the first time we are seeing this word
  34.    
  35.     word_list = contents.split()
  36.     #print word_list
  37.  
  38.     for word in word_list:
  39.         if word not in result:
  40.             result[word] = [1]
  41.         else:
  42.             result[word].append(+1)
  43.  
  44.     print result
  45.        
  46.  
  47.  
  48. open_file(filepath)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement