データクレンジングにあたり必要な機能のPythonでの実装方法の確認が一通り終わったので組み合わせてデータ変換プログラムを完成させる。
convert_ratings.py
# -*- coding: utf-8 -*- import sys if __name__ == "__main__": arg = sys.argv input_file = arg[1] output_file = arg[2] with open(input_file, 'r') as in_file: with open(output_file, 'w') as out_file: rows = 0 for line in in_file: rows += 1 # 先頭行はヘッダなのでスキップ if rows == 1: continue list = line.split(",") restaurant_id = list[1] # ユーザーIDは16進->10進変換 user_id = long(list[2], 16) total = list[3] out_file.write(str(user_id) + "," + restaurant_id + "," + total + "\n") if rows % 1000 == 0: print(str(rows) + "行変換しました。") print(str(rows) + "行変換しました。")
まあ、こんな感じで。
では、ようやく変換を。
$ python convert_ratings.py ratings.csv ldgourmet_ratings_for_ibr2.csv 1000行変換しました。 2000行変換しました。 (省略) 205833行変換しました。 $ head ldgourmet_ratings_for_ibr2.csv 3993170538,310595,5 4240577537,10237,1 104934135,3334,2 104934135,15163,5 1290717597,567,3 1290717597,1026,5 1290717597,1058,5 1290717597,2569,3 1290717597,3309,4 1290717597,3648,4
バッチリ。
とりあえず今日はここまでにして、次回いよいよ協調フィルタリングに再挑戦。