forked from p46318075/CodePattern
You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
43 lines
1.4 KiB
43 lines
1.4 KiB
from sqlalchemy import create_engine, Column, Integer, String, ForeignKey
|
|
from sqlalchemy.ext.declarative import declarative_base
|
|
from sqlalchemy.orm import relationship
|
|
import os
|
|
from cppy.cp_util import db_filename
|
|
|
|
|
|
# 定义数据模型和数据库连接
|
|
Base = declarative_base()
|
|
|
|
# 获取当前文件所在的目录
|
|
current_dir = os.path.dirname(os.path.abspath(__file__))
|
|
|
|
# 构造数据库文件的完整路径
|
|
db_file_path = os.path.join(current_dir, db_filename)
|
|
DATABASE_URI = f"sqlite:///{db_file_path}"
|
|
|
|
# 创建数据库引擎
|
|
engine = create_engine(DATABASE_URI, echo=True)
|
|
|
|
|
|
class TextFile(Base):
|
|
__tablename__ = 'text_files'
|
|
id = Column(Integer, primary_key=True)
|
|
filepath = Column(String, unique=True)
|
|
content = Column(String)
|
|
words = relationship("WordFrequency", back_populates="textfile")
|
|
|
|
class WordFrequency(Base):
|
|
__tablename__ = 'word_frequencies'
|
|
id = Column(Integer, primary_key=True)
|
|
word = Column(String)
|
|
frequency = Column(Integer)
|
|
textfile_id = Column(Integer, ForeignKey('text_files.id'))
|
|
textfile = relationship("TextFile", back_populates="words")
|
|
|
|
|
|
if __name__ == '__main__':
|
|
# 检查数据库文件是否存在
|
|
if os.path.exists(db_file_path):
|
|
os.remove(db_file_path)
|
|
|
|
Base.metadata.create_all(engine) |