Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- # Exercise G
- # Use the sys argv to get the argument from the command line and store it
- filepath = sys.argv[1]
- #print filepath
- # Define a function that opens the given file and counts the words
- def open_file(filepath):
- # open the file and read its contents into a variable
- with open(filepath, "r") as my_file:
- contents = my_file.read()
- #print contents
- # We need to loop over each word in the content string.
- # Convert the string into a list of words
- # For each word in the list of words we need to have a place to store how often we've seen it.
- # 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.
- # Make an empty dictionary to store our words
- result = {}
- # FOR LOOP
- # For each word in the list, check if we've seen it already. Similar to last week...
- # If we have seen it we can add 1 to that count
- # If we haven't seen it we can se the count to 1 as it's the first time we are seeing this word
- word_list = contents.split()
- #print word_list
- for word in word_list:
- if word not in result:
- result[word] = [1]
- else:
- result[word].append(+1)
- print result
- open_file(filepath)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement