JustZiya

将豆瓣已看电影写入Sqlite


# -*- coding: utf-8 -*-

from peewee import *
import datetime
import csv
import re

db = SqliteDatabase("movie.sqlite")

class BaseModel(Model):
    class Meta:
        database = db


class Movie(BaseModel):
    Douban_Url = CharField(unique=True)
    IMDB = CharField(default='')
    CN_name = CharField()
    OG_name = CharField()
    Update_time = DateTimeField(default=datetime.datetime.now)
    is_check=IntegerField(default=0)

class Watched(BaseModel):
    Date = CharField()
    Watched_movie = ForeignKeyField(Movie)
    Score = IntegerField()
    Comment = TextField()


class Tags(BaseModel):
    name = CharField(unique=True)


class Movie_Tags(BaseModel):
    Movie = ForeignKeyField(Movie)
    Tags = ForeignKeyField(Tags)

    class Meta:
        indexes = ((("Movie", "Tags"), True),)

def create_tables():
    with db:
        db.create_tables([Movie, Watched, Tags, Movie_Tags])


if __name__ == "__main__":
    create_tables()
    with open("movie.csv", "r") as csvFile:
        dict_reader = csv.reader(csvFile, delimiter="|")
        for i in dict_reader:
            # 处理电影
            try:
                movies = Movie.create(Douban_Url=i[0], CN_name=i[1], OG_name=i[2])
                movies.save()
            except:
                movies = Movie.get(Movie.CN_name == i[1])
            # 处理标签
            if i[5]:
                for t in i[5].split(" "):
                    try:
                        tag = Tags.create(name=t)
                        tag.save()
                    except:
                        tag = Tags.get(Tags.name == t)
                    # print(movies.id,t,tag.id)
            # 处理电影标签
            try:
                movietag = Movie_Tags.create(Movie=movies, Tags=tag)
                movietag.save()
            except:
                pass
            # 处理已看信息
            try:
                moviewatch = Watched.create(
                    Date=i[3], Watched_movie=movies, Score=int(i[4]), Comment=i[6]
                )
                movietag.save
            except:
                pass


评论