#Coding=utf-8ImportSYSImportOS##==================================#load the specified training set file#parameter filename for a training set file##==================================defLoadmovielenstrain (filename='U1.base'): str1='./movielens/' #relative address of the directoryprefer= {} forLineinchOpen (Str1+filename,'R'):#Open the specified file(UserID, MovieID, rating,ts) = Line.split ('\ t')#4 items per row in the data setPrefer.setdefault (userid, {})#set the default format of the dictionary, the element is user:{} dictionaryPrefer[userid][movieid] =Float (rating)returnPrefer#format such as {: ' user1 ' {itemid:rating, itemid2:rating,,,}, {,,,}}##==================================#load the corresponding test set file#the parameter, filename, represents a test set file, such as U1.test##==================================defLoadmovielenstest (filename='u1.test'): str1='./movielens/'prefer= {} forLineinchOpen (Str1+filename,'R'): (UserID, MovieID, Rating,ts)= Line.split ('\ t')#4 items per row in the data setPrefer.setdefault (userid, {}) Prefer[userid][movieid]=Float (rating)returnpreferif __name__=="__main__": Print("""This section can perform the above 2 function tests""") Traindict=Loadmovielenstrain () testdict=loadmovielenstest ()Print(Len (traindict))Print(Len (testdict))Print("""Test Pass""")
Collaborative Filtering Code---loadmovielens.py file