In-class notes for 03/19/2014 (CS 121B (CS1), Spring 2014)
>>     < >




In-class notes for 03/19/2014

CS 121B (CS1), Spring 2014

Submitted questions on assignments and technology

Upcoming

Summary of strings chapter

Files

  • open()

  • Traversing line-by-line with a for loop

  • Methods close(), read(), write()

Dictionaries

Exercises

  • Exercise: Write a function that reads lines from a file and returns a dictionary containing frequency counts for all the words in that file.

    countWords

    One argument: A string, representing a file name
    Return: A dictionary whose keys are the words found in that file arg1, and whose values are the number of occurrences of those words in that file arg1.
    Example calls:
        countWords("cathat.txt")) 
        --> {'The':1, 'cat':2, 'in':1, 'the':3, 'hat':3, 'wore':1, 'to':1, 'party':1}
    

    Hints:

    • Use open() and close() to create a connection to the file near the beginning of your function and to disconnect near the end of your function.

    • The dictionary contains accumulators for all of the words found in that file.

    • Check to see if a word's count is already present in the dictionary. Example:

          words = { 'The': 1, 'cat': 1, 'in': 1 }
          'cat' in words --> True
          'hat' in words --> False
      
      If a word isn't already a key, assign 1 to that key in the dictionary; otherwise, increment that key's prior value.

  • Exercise: Write a function that reads lines from a netflix data file and returns a dictionary containing frequency counts of ratings for each movie.

    countRatings

    One argument: A string, representing the name of a netflix data file.
    Return: A dictionary whose keys are the movie ids found in that file arg1, and whose values are the number of ratings given by all reviewers to that movie in that file arg1. Return False if the data file fails to open.
    Example calls:
        countRatings("netflix.dat")) 
        --> {1:3, 2:1, 3:7, 5:7, 6:6, 8:22}
    

    Hints:

Submitted questions on readings




< >