├── .gitignore
├── .idea
├── BookRecommend.iml
├── inspectionProfiles
│ └── profiles_settings.xml
├── misc.xml
├── modules.xml
└── vcs.xml
├── BookRecommend
├── __init__.py
├── __pycache__
│ ├── __init__.cpython-36.pyc
│ ├── settings.cpython-36.pyc
│ ├── urls.cpython-36.pyc
│ └── wsgi.cpython-36.pyc
├── asgi.py
├── settings.py
├── urls.py
└── wsgi.py
├── README.en.md
├── README.md
├── __pycache__
└── manage.cpython-36.pyc
├── data
├── 2016-2018借书.xlsx
├── CF_user_calculate.py
├── __init__.py
├── admin.py
├── apps.py
├── data_cleansing.py
├── migrations
│ ├── 0001_initial.py
│ └── __init__.py
├── models.py
├── tests.py
└── views.py
├── db.sqlite3
└── manage.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
2 | # Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
3 |
4 | # User-specific stuff
5 | .idea/**/workspace.xml
6 | .idea/**/tasks.xml
7 | .idea/**/usage.statistics.xml
8 | .idea/**/dictionaries
9 | .idea/**/shelf
10 |
11 | # Generated files
12 | .idea/**/contentModel.xml
13 |
14 | # Sensitive or high-churn files
15 | .idea/**/dataSources/
16 | .idea/**/dataSources.ids
17 | .idea/**/dataSources.local.xml
18 | .idea/**/sqlDataSources.xml
19 | .idea/**/dynamic.xml
20 | .idea/**/uiDesigner.xml
21 | .idea/**/dbnavigator.xml
22 |
23 | # Gradle
24 | .idea/**/gradle.xml
25 | .idea/**/libraries
26 |
27 | # Gradle and Maven with auto-import
28 | # When using Gradle or Maven with auto-import, you should exclude module files,
29 | # since they will be recreated, and may cause churn. Uncomment if using
30 | # auto-import.
31 | # .idea/modules.xml
32 | # .idea/*.iml
33 | # .idea/modules
34 |
35 | # CMake
36 | cmake-build-*/
37 |
38 | # Mongo Explorer plugin
39 | .idea/**/mongoSettings.xml
40 |
41 | # File-based project format
42 | *.iws
43 |
44 | # IntelliJ
45 | out/
46 |
47 | # mpeltonen/sbt-idea plugin
48 | .idea_modules/
49 |
50 | # JIRA plugin
51 | atlassian-ide-plugin.xml
52 |
53 | # Cursive Clojure plugin
54 | .idea/replstate.xml
55 |
56 | # Crashlytics plugin (for Android Studio and IntelliJ)
57 | com_crashlytics_export_strings.xml
58 | crashlytics.properties
59 | crashlytics-build.properties
60 | fabric.properties
61 |
62 | # Editor-based Rest Client
63 | .idea/httpRequests
64 |
65 | # Android studio 3.1+ serialized cache file
66 | .idea/caches/build_file_checksums.ser
67 | data/__pycache__/
68 | data/migrations/__pycache__/
69 | static/
70 | templates/
71 | "data/~$2016-2018\345\200\237\344\271\246.xlsx"
72 | /data/2016-2018借书.xlsx
73 | /data/~$2016-2018借书.xlsx
74 | /data/bdataReaded.xlsx
75 | /data/data_readerinfo.xlsx
76 | /data/rdataReaded.xlsx
77 |
--------------------------------------------------------------------------------
/.idea/BookRecommend.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
27 |
28 |
29 |
30 |
31 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/BookRecommend/__init__.py:
--------------------------------------------------------------------------------
1 | import pymysql
2 | pymysql.install_as_MySQLdb()
--------------------------------------------------------------------------------
/BookRecommend/__pycache__/__init__.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Banner-Studio/BookRecommendationSystem/e9554301cf8862e3930213f9e67b1b50c6fefde5/BookRecommend/__pycache__/__init__.cpython-36.pyc
--------------------------------------------------------------------------------
/BookRecommend/__pycache__/settings.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Banner-Studio/BookRecommendationSystem/e9554301cf8862e3930213f9e67b1b50c6fefde5/BookRecommend/__pycache__/settings.cpython-36.pyc
--------------------------------------------------------------------------------
/BookRecommend/__pycache__/urls.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Banner-Studio/BookRecommendationSystem/e9554301cf8862e3930213f9e67b1b50c6fefde5/BookRecommend/__pycache__/urls.cpython-36.pyc
--------------------------------------------------------------------------------
/BookRecommend/__pycache__/wsgi.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Banner-Studio/BookRecommendationSystem/e9554301cf8862e3930213f9e67b1b50c6fefde5/BookRecommend/__pycache__/wsgi.cpython-36.pyc
--------------------------------------------------------------------------------
/BookRecommend/asgi.py:
--------------------------------------------------------------------------------
1 | """
2 | ASGI config for BookRecommend project.
3 |
4 | It exposes the ASGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.asgi import get_asgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BookRecommend.settings')
15 |
16 | application = get_asgi_application()
17 |
--------------------------------------------------------------------------------
/BookRecommend/settings.py:
--------------------------------------------------------------------------------
1 | """
2 | Django settings for BookRecommend project.
3 |
4 | Generated by 'django-admin startproject' using Django 3.0.2.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.0/topics/settings/
8 |
9 | For the full list of settings and their values, see
10 | https://docs.djangoproject.com/en/3.0/ref/settings/
11 | """
12 |
13 | import os
14 | # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
15 | BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
16 |
17 |
18 | # Quick-start development settings - unsuitable for production
19 | # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
20 |
21 | # SECURITY WARNING: keep the secret key used in production secret!
22 | SECRET_KEY = 'd^gimyj161l&ho2#@r3&w1a3e(2p%q)r6x7+7e)8ge4k=&=mz6'
23 |
24 | # SECURITY WARNING: don't run with debug turned on in production!
25 | DEBUG = True
26 |
27 | ALLOWED_HOSTS = []
28 |
29 |
30 | # Application definition
31 |
32 | INSTALLED_APPS = [
33 | 'django.contrib.admin',
34 | 'django.contrib.auth',
35 | 'django.contrib.contenttypes',
36 | 'django.contrib.sessions',
37 | 'django.contrib.messages',
38 | 'django.contrib.staticfiles',
39 | 'data.apps.DataConfig',
40 | # 'data',
41 | ]
42 |
43 | MIDDLEWARE = [
44 | 'django.middleware.security.SecurityMiddleware',
45 | 'django.contrib.sessions.middleware.SessionMiddleware',
46 | 'django.middleware.common.CommonMiddleware',
47 | 'django.middleware.csrf.CsrfViewMiddleware',
48 | 'django.contrib.auth.middleware.AuthenticationMiddleware',
49 | 'django.contrib.messages.middleware.MessageMiddleware',
50 | 'django.middleware.clickjacking.XFrameOptionsMiddleware',
51 | ]
52 |
53 | ROOT_URLCONF = 'BookRecommend.urls'
54 |
55 | TEMPLATES = [
56 | {
57 | 'BACKEND': 'django.template.backends.django.DjangoTemplates',
58 | 'DIRS': [],
59 | 'APP_DIRS': True,
60 | 'OPTIONS': {
61 | 'context_processors': [
62 | 'django.template.context_processors.debug',
63 | 'django.template.context_processors.request',
64 | 'django.contrib.auth.context_processors.auth',
65 | 'django.contrib.messages.context_processors.messages',
66 | ],
67 | },
68 | },
69 | ]
70 |
71 | WSGI_APPLICATION = 'BookRecommend.wsgi.application'
72 |
73 |
74 | # Database
75 | # https://docs.djangoproject.com/en/3.0/ref/settings/#databases
76 |
77 | DATABASES = {
78 | 'default': {
79 | 'ENGINE': 'django.db.backends.mysql',
80 | # 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
81 | 'NAME': 'book_recommend', # 使用的数据库名字,数据库必须手动创建
82 | 'USER': 'root', # 连接mysql的用户名
83 | 'PASSWORD': '123456', # 用户对应的密码
84 | 'HOST': 'localhost', # 指定mysql数据库所在电脑ip
85 | 'PORT': 3306,
86 | }
87 | }
88 |
89 |
90 | # Password validation
91 | # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
92 |
93 | AUTH_PASSWORD_VALIDATORS = [
94 | {
95 | 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
96 | },
97 | {
98 | 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
99 | },
100 | {
101 | 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
102 | },
103 | {
104 | 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
105 | },
106 | ]
107 |
108 |
109 | # Internationalization
110 | # https://docs.djangoproject.com/en/3.0/topics/i18n/
111 |
112 | LANGUAGE_CODE = 'zh-hans'
113 |
114 | TIME_ZONE = 'Asia/Shanghai'
115 |
116 | USE_I18N = True
117 |
118 | USE_L10N = True
119 |
120 | USE_TZ = True
121 |
122 |
123 | # Static files (CSS, JavaScript, Images)
124 | # https://docs.djangoproject.com/en/3.0/howto/static-files/
125 |
126 | STATIC_URL = '/static/'
127 |
128 | # 设置静态文件存放的物理目录
129 | STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
130 | # 配置上传文件的存放路径
131 | MEDIA_ROOT = os.path.join(BASE_DIR, 'static/media')
132 |
--------------------------------------------------------------------------------
/BookRecommend/urls.py:
--------------------------------------------------------------------------------
1 | """BookRecommend URL Configuration
2 |
3 | The `urlpatterns` list routes URLs to views. For more information please see:
4 | https://docs.djangoproject.com/en/3.0/topics/http/urls/
5 | Examples:
6 | Function views
7 | 1. Add an import: from my_app import views
8 | 2. Add a URL to urlpatterns: path('', views.home, name='home')
9 | Class-based views
10 | 1. Add an import: from other_app.views import Home
11 | 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
12 | Including another URLconf
13 | 1. Import the include() function: from django.urls import include, path
14 | 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
15 | """
16 | from django.contrib import admin
17 | from django.urls import path
18 |
19 | urlpatterns = [
20 | path('admin/', admin.site.urls),
21 | ]
22 |
--------------------------------------------------------------------------------
/BookRecommend/wsgi.py:
--------------------------------------------------------------------------------
1 | """
2 | WSGI config for BookRecommend project.
3 |
4 | It exposes the WSGI callable as a module-level variable named ``application``.
5 |
6 | For more information on this file, see
7 | https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
8 | """
9 |
10 | import os
11 |
12 | from django.core.wsgi import get_wsgi_application
13 |
14 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BookRecommend.settings')
15 |
16 | application = get_wsgi_application()
17 |
--------------------------------------------------------------------------------
/README.en.md:
--------------------------------------------------------------------------------
1 | # 图书推荐系统
2 |
3 | #### Description
4 | 图书推荐系统 开发框架django 开发环境Pycharm python 3.6 数据库mysql@author YangYang ZhangXinYu
5 |
6 |
7 | #### Software Architecture
8 | Software architecture description
9 |
10 | #### Installation
11 |
12 | 1. xxxx
13 | 2. xxxx
14 | 3. xxxx
15 |
16 | #### Instructions
17 |
18 | 1. xxxx
19 | 2. xxxx
20 | 3. xxxx
21 |
22 | #### Contribution
23 |
24 | 1. Fork the repository
25 | 2. Create Feat_xxx branch
26 | 3. Commit your code
27 | 4. Create Pull Request
28 |
29 |
30 | #### Gitee Feature
31 |
32 | 1. You can use Readme\_XXX.md to support different languages, such as Readme\_en.md, Readme\_zh.md
33 | 2. Gitee blog [blog.gitee.com](https://blog.gitee.com)
34 | 3. Explore open source project [https://gitee.com/explore](https://gitee.com/explore)
35 | 4. The most valuable open source project [GVP](https://gitee.com/gvp)
36 | 5. The manual of Gitee [https://gitee.com/help](https://gitee.com/help)
37 | 6. The most popular members [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
38 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 图书推荐系统
2 |
3 | #### 介绍
4 | 图书推荐系统 开发框架django 开发环境Pycharm python 3.6 数据库mysql@author YangYang ZhangXinYu
5 |
6 |
7 | #### 软件架构
8 | 软件架构说明
9 |
10 |
11 | #### 安装教程
12 |
13 | 1. xxxx
14 | 2. xxxx
15 | 3. xxxx
16 |
17 | #### 使用说明
18 |
19 | 1. xxxx
20 | 2. xxxx
21 | 3. xxxx
22 |
23 | #### 参与贡献
24 |
25 | 1. Fork 本仓库
26 | 2. 新建 Feat_xxx 分支
27 | 3. 提交代码
28 | 4. 新建 Pull Request
29 |
30 |
31 | #### 码云特技
32 |
33 | 1. 使用 Readme\_XXX.md 来支持不同的语言,例如 Readme\_en.md, Readme\_zh.md
34 | 2. 码云官方博客 [blog.gitee.com](https://blog.gitee.com)
35 | 3. 你可以 [https://gitee.com/explore](https://gitee.com/explore) 这个地址来了解码云上的优秀开源项目
36 | 4. [GVP](https://gitee.com/gvp) 全称是码云最有价值开源项目,是码云综合评定出的优秀开源项目
37 | 5. 码云官方提供的使用手册 [https://gitee.com/help](https://gitee.com/help)
38 | 6. 码云封面人物是一档用来展示码云会员风采的栏目 [https://gitee.com/gitee-stars/](https://gitee.com/gitee-stars/)
39 |
--------------------------------------------------------------------------------
/__pycache__/manage.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Banner-Studio/BookRecommendationSystem/e9554301cf8862e3930213f9e67b1b50c6fefde5/__pycache__/manage.cpython-36.pyc
--------------------------------------------------------------------------------
/data/2016-2018借书.xlsx:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Banner-Studio/BookRecommendationSystem/e9554301cf8862e3930213f9e67b1b50c6fefde5/data/2016-2018借书.xlsx
--------------------------------------------------------------------------------
/data/CF_user_calculate.py:
--------------------------------------------------------------------------------
1 |
2 | import math
3 | import os
4 | import django
5 | os.environ.setdefault("DJANGO_SETTINGS_MODULE", "BookRecommend.settings")
6 | django.setup()
7 |
8 | from data.models import ReaderInfo, BookInfo
9 |
10 |
11 | class UserCf:
12 | """基于用户的协调过滤算法类"""
13 | def __init__(self):
14 | # 建立一个字典,存放相似用户和相似度
15 | self.user_sim_dict = {}
16 | # 建立一个字典,存放推荐给目标用户的书籍的感兴趣程度
17 | self.user_book_interest_dict = {}
18 |
19 | def user_sim(self, target_user_rid):
20 | """计算用户相似度"""
21 | # 基于目标用户rid获取目标用户id
22 | target_user = ReaderInfo.objects.get(rid=target_user_rid)
23 | target_user_id = target_user.id
24 | # 基于目标用户id获取目标用户读过的书籍
25 | # 基于列去重
26 | target_user_books = BookInfo.objects.filter(breader=target_user_id).distinct() .order_by('bname')
27 | # 基于目标用户读过的书籍获取相似用户
28 | # self.user_sim_dict = {}
29 | print(target_user_books)
30 | for target_user_book in target_user_books:
31 | users = ReaderInfo.objects.filter(bookinfo__bname=target_user_book.bname)
32 | for user in users:
33 | self.user_sim_dict[user.id] = 0
34 | if target_user.id in self.user_sim_dict.keys():
35 | del self.user_sim_dict[target_user_id]
36 | print(str(self.user_sim_dict))
37 | # 计算用户相似度:
38 | # 获取目标用户读过的书的数量
39 | target_user_books_num = target_user_books.count()
40 | # 假设相似用户和目标用户读过的相同书量为0
41 | book_same_num = 0
42 | # 假设用户相似度为0
43 | user_similarity = 0
44 | for user_sim_id in self.user_sim_dict:
45 | # 获取相似用户读过的书的数量
46 | user_sim_book_num = BookInfo.objects.filter(breader=user_sim_id).count()
47 | for target_user_book in target_user_books:
48 | book_same_num1 = BookInfo.objects.filter(bname=target_user_book, breader=user_sim_id)
49 | book_same_num += book_same_num1.count()
50 | # 获取和目标用户读过的书相同的相似用户数目
51 | user_book_same_num = ReaderInfo.objects.filter(bookinfo__bname=target_user_book)\
52 | .exclude(id=target_user_id).count()
53 | if user_book_same_num:
54 | user_similarity1 = book_same_num*1 / (math.log(1) + user_book_same_num)
55 | else:
56 | user_similarity1 = 0
57 | user_similarity += user_similarity1
58 | user_similarity = user_similarity/math.sqrt(target_user_books_num * user_sim_book_num)
59 | # print(user_similarity)
60 | self.user_sim_dict[user_sim_id] = user_similarity
61 | # print(user_sim_book_num)
62 | print(str(self.user_sim_dict))
63 | print('结束')
64 | return self.user_sim_dict
65 |
66 | def target_user_book_interest(self):
67 | """用UserCF算法计算目标用户对物品的感兴趣程度"""
68 |
69 | # 基于相似用户寻找推荐的书籍
70 | user_sim_dict = self.user_sim_dict.copy()
71 | user_sim_dict = {k: v for k, v in user_sim_dict.items() if v < 15}
72 | print(str(user_sim_dict))
73 | user_sim_dict = dict(sorted(user_sim_dict.items(), key=lambda ud: ud[1], reverse=True))
74 | print(str(user_sim_dict))
75 | # 建立一个字典,存放推荐给目标用户的书籍的感兴趣程度
76 | # self.user_book_interest = {}
77 | for user_sim_id in user_sim_dict:
78 | user_sim_books = BookInfo.objects.filter(breader=user_sim_id)
79 | for user_sim_book in user_sim_books:
80 | self.user_book_interest_dict[user_sim_book.bname] = 0
81 | for user_sim_id_other in user_sim_dict:
82 | if BookInfo.objects.filter(breader=user_sim_id_other, bname=user_sim_book).count():
83 | self.user_book_interest_dict[user_sim_book.bname] += user_sim_dict[user_sim_id]
84 | self.user_book_interest_dict = dict(sorted(self.user_book_interest_dict.items(), key=lambda ud: ud[1],
85 | reverse=True))
86 | print(str(self.user_book_interest_dict))
87 |
88 |
89 | usercf = UserCf()
90 | usercf.user_sim(20151435113)
91 | # 20150934106
92 | usercf.target_user_book_interest()
--------------------------------------------------------------------------------
/data/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Banner-Studio/BookRecommendationSystem/e9554301cf8862e3930213f9e67b1b50c6fefde5/data/__init__.py
--------------------------------------------------------------------------------
/data/admin.py:
--------------------------------------------------------------------------------
1 | from django.contrib import admin
2 | from data.models import BookInfo, ReaderInfo
3 | # Register your models here.
4 |
5 |
6 | class BookInfoStackedInline(admin.StackedInline):
7 | # 写多类的名字
8 | model = BookInfo
9 | # extra = 2
10 | # raw_id_fields = ("breader",)
11 | fk_name = 'breader'
12 |
13 |
14 | class BookInfoAdmin(admin.ModelAdmin):
15 | """图书模型管理类 """
16 | list_display = ['id', 'bname', 'baddress', 'breader']
17 | # list_filter = ['bname'] # 列表页右侧过滤栏
18 | search_fields = ['bname', 'baddress', 'breader__rid'] # 列表页上方的搜索栏
19 | # readonly_fields = ('id', 'breader')
20 | ordering = ('baddress', 'breader')
21 |
22 |
23 | class ReaderInfoAdmin(admin.ModelAdmin):
24 | """读者模型管理类"""
25 | list_display = ['id', 'rid', 'rname']
26 | inlines = [BookInfoStackedInline]
27 | search_fields = ['rid'] # 列表页上方的搜索栏
28 | ordering = ('rid',)
29 | # readonly_fields = ('id',)
30 |
31 |
32 | # #注册模型类
33 |
34 | admin.site.register(ReaderInfo, ReaderInfoAdmin)
35 |
36 |
37 | admin.site.register(BookInfo, BookInfoAdmin)
38 |
39 |
--------------------------------------------------------------------------------
/data/apps.py:
--------------------------------------------------------------------------------
1 | from django.apps import AppConfig
2 |
3 |
4 | class DataConfig(AppConfig):
5 | name = 'data'
6 |
--------------------------------------------------------------------------------
/data/data_cleansing.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import pandas as pd
3 | import re
4 | import time
5 | import threading
6 | # 进行数据清洗,将需要的数据导入到数据库中
7 |
8 | dataReaded = pd.read_excel('2016-2018借书.xlsx')
9 |
10 |
11 | def clean(df, pattern=r'(2\d{10})'):
12 | """筛选出可利用的数据"""
13 | r = df.tolist()
14 | p = []
15 | for i in r:
16 | r = re.findall(pattern, str(i))
17 | if len(r) > 0:
18 | # print(r)
19 | p.append(int(r[0]))
20 | return p
21 |
22 |
23 | # 去重
24 | rdataReaded = dataReaded[['读者号', '读者']].drop_duplicates(['读者号', '读者'])
25 | # 清洗数据
26 | rdataReaded = rdataReaded.where(rdataReaded['读者号'].isin(clean(rdataReaded['读者号'])))
27 | rdataReaded = rdataReaded.dropna(axis=0)
28 | print('开始存数据1')
29 | # 存数据到excel表格中
30 | rdataReaded.to_excel('rdataReaded.xlsx', index=False, sheet_name='rdataReaded')
31 |
32 |
33 | bdataReaded = dataReaded[['题名', '馆藏', '读者号']]
34 | bdataReaded = bdataReaded.where(bdataReaded['读者号'].isin(clean(bdataReaded['读者号'])))
35 | bdataReaded = bdataReaded.dropna(axis=0)
36 | print('开始存数据2')
37 | # 存数据到excel表格中
38 | bdataReaded.to_excel('bdataReaded.xlsx', index=False, sheet_name='bdataReaded')
39 |
40 | # 读取数据
41 | data_readerinfo = pd.read_excel('data_readerinfo.xlsx')
42 | bdataReaded['读者号id'] = 0
43 | it1 = iter(range(bdataReaded.shape[0]))
44 | start = time.clock()
45 |
46 |
47 | class GetIdThread(threading.Thread):
48 | """单线程"""
49 | def __init__(self):
50 | threading.Thread.__init__(self)
51 |
52 | def run(self):
53 | print('开始线程')
54 | get_id_main()
55 | print('退出线程')
56 |
57 |
58 | def get_id_main():
59 | """根据另一个表中的数据,修改本表的数据"""
60 | while True:
61 | try:
62 | r1 = next(it1)
63 | it2 = iter(range(data_readerinfo.shape[0]))
64 | for r2 in it2:
65 | if bdataReaded.iloc[r1, 2] == data_readerinfo.iloc[r2, 1]:
66 | bdataReaded.iloc[r1, 3] = data_readerinfo.iloc[r2, 0]
67 | print(bdataReaded.iloc[r1, 3])
68 | break
69 |
70 | except StopIteration:
71 | print('用时:', time.clock() - start)
72 | bdata_readed = bdataReaded.drop_duplicates(subset=['题名', '读者号id'])
73 | bdata_readed.to_excel('bdataReaded.xlsx', index=False, sheet_name='new_bdataReaded')
74 | sys.exit()
75 |
76 |
77 | thread = GetIdThread()
78 | thread.start()
79 | thread.join()
80 | print('退出主线程')
81 |
--------------------------------------------------------------------------------
/data/migrations/0001_initial.py:
--------------------------------------------------------------------------------
1 | # Generated by Django 3.0.2 on 2020-02-06 05:33
2 |
3 | from django.db import migrations, models
4 | import django.db.models.deletion
5 |
6 |
7 | class Migration(migrations.Migration):
8 |
9 | initial = True
10 |
11 | dependencies = [
12 | ]
13 |
14 | operations = [
15 | migrations.CreateModel(
16 | name='ReaderInfo',
17 | fields=[
18 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
19 | ('rid', models.CharField(max_length=20)),
20 | ('rname', models.CharField(max_length=20)),
21 | ],
22 | options={
23 | 'db_table': 'readerInfo',
24 | },
25 | ),
26 | migrations.CreateModel(
27 | name='BookInfo',
28 | fields=[
29 | ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
30 | ('baddress', models.CharField(max_length=20)),
31 | ('bname', models.CharField(max_length=100)),
32 | ('breader', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='data.ReaderInfo')),
33 | ],
34 | options={
35 | 'db_table': 'bookInfo',
36 | },
37 | ),
38 | ]
39 |
--------------------------------------------------------------------------------
/data/migrations/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Banner-Studio/BookRecommendationSystem/e9554301cf8862e3930213f9e67b1b50c6fefde5/data/migrations/__init__.py
--------------------------------------------------------------------------------
/data/models.py:
--------------------------------------------------------------------------------
1 | from django.db import models
2 |
3 | # Create your models here.
4 |
5 |
6 | class BookInfo(models.Model):
7 | """图书信息模型类"""
8 | # 馆藏地址
9 | baddress = models.CharField(max_length=20)
10 | # 书名
11 | bname = models.CharField(max_length=100)
12 | # 图书与读者的关系
13 | breader = models.ForeignKey('ReaderInfo', on_delete=models.CASCADE)
14 |
15 | def __str__(self):
16 | """返回书名"""
17 | return self.bname
18 |
19 | class Meta:
20 | db_table = 'bookInfo'
21 |
22 |
23 | class ReaderInfo(models.Model):
24 | """读者信息模型类"""
25 | # 读者号
26 | rid = models.CharField(max_length=20)
27 | # 读者名
28 | rname = models.CharField(max_length=20)
29 |
30 | class Meta:
31 | db_table = 'readerInfo'
32 |
33 | def __str__(self):
34 | """返回读者号"""
35 | return self.rid
36 |
37 |
--------------------------------------------------------------------------------
/data/tests.py:
--------------------------------------------------------------------------------
1 | from django.test import TestCase
2 |
3 | # Create your tests here.
4 |
--------------------------------------------------------------------------------
/data/views.py:
--------------------------------------------------------------------------------
1 | from django.shortcuts import render
2 | from django.http import HttpResponse
3 | # Create your views here.
4 | #定义视图函数,HttpResquest
5 | #进行url配置建立url地址和视图对应的关系
6 | #http://127.0.0.1:8000/index
7 |
8 |
--------------------------------------------------------------------------------
/db.sqlite3:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Banner-Studio/BookRecommendationSystem/e9554301cf8862e3930213f9e67b1b50c6fefde5/db.sqlite3
--------------------------------------------------------------------------------
/manage.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python
2 | """Django's command-line utility for administrative tasks."""
3 | import os
4 | import sys
5 |
6 |
7 | def main():
8 | os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'BookRecommend.settings')
9 | try:
10 | from django.core.management import execute_from_command_line
11 | except ImportError as exc:
12 | raise ImportError(
13 | "Couldn't import Django. Are you sure it's installed and "
14 | "available on your PYTHONPATH environment variable? Did you "
15 | "forget to activate a virtual environment?"
16 | ) from exc
17 | execute_from_command_line(sys.argv)
18 |
19 |
20 | if __name__ == '__main__':
21 | main()
22 |
--------------------------------------------------------------------------------