基于文本内容的推荐系统开发记录
系统开发
系统架构设计
浏览:1121 次

基于文本内容的推荐系统开发记录
这将涉及:
推荐的模型逻辑
算法的基本实现和测试(调用gensim等模块)
内存溢出问题的解决方案
编写Python rest服务接口
推荐的模型逻辑
模块逻辑类图
基本思想是围绕一个json文件展开,将文本对应信息保存在json中,并根据更新的字典和语料库定期更新json。
算法的基本实现和测试
文本预处理
中文文本的预处理包括标点符号去除、停止词去除和分词(单独编辑为预处理模块)
类预处理():
关键词=[]
stopword_filepath=“./stopwordList/stopword.txt”
定义__初始__(自身):
自我__readin_ stop()
定义__读取_停止(自身):
file_obj=编解码器打开(self.stopword_filepath,'r','utf-8')
当为真时:
line=file_obj.readline()
line=line.strip(“\r\n”)
如果不是行:
打破
self.stopwords.append(行)
文件_对象关闭()
def clean_ doc(self,doc):
#中文字符的Unicode范围为4e00-9fa5
模式=重新编译(r'[\u4e00-\u9fa5]+')
filter_data=re.findall(模式,文档)
cleaned_ doc=“”.join(filter_data)
返回清洁文档

def cut(自身,文档):
seg=jieba.cut(文档)
结果=[]
对于seg中的项目:
如果项目在self.stopwords中:
持续
results.append(项)
返回结果
该模块输入未处理的文本字符串,并在分词后输出数组。
词典和语料库建设
字典是输入所有当前文本分词结果dict=[(w1,id),(w2,id)、(w3,id)…,(wn,id)]
语料库的格式是在字典中生成相应的文本:
语料库=[
[
#文档1
(w,id),(w,id),(w,id)…..(w,id)
],[
#文档2
(w,id),(w,id),……(w,id)
],
......[
#文件_ n
]
]
以上是语料库的基本格式
定义_集合_原始_语料库(自身):
if(os.listdir()中的'dictionary.txt'):
打印(“--------语料库已构建--------”)
自己dictionary=corporate.dictionary。load_ from_ text('dictionary.txt')
回来
使用open('doc.json','r',encoding='gbk')作为f:
doc=json.load(f)

语料库=[]
文本=[]
#预处理模块介绍
pre=预处理()
对于文档中的文档项:
打开(self.dir+doc_item['name'],'r',encoding='gbk')作为f:
text.append(f.read())
对于文本中的项目:
pre_ doc=pre.cut(pre.clean_doc(item))
语料库追加(pre_doc)
dictionary=语料库.dictionary(语料库)
#将字典库另存为txt
词典save_ as_ text('dictionary.txt')
公司=[]
打印('----------字典构造已完成,当前共有%d个单词:%d----------'%len(dictionary.keys()))
对于文本中的项目:
corp.append(dictionary.doc2ow(pre.cut(pre.clean_doc(item)))
#将语料库存储为pkl序列
打开('corpus.pkl','wb')为f:
pickle.dump(公司,f)
自己corp=公司
打印('----------语料库建设完成---------')
如您所见,语料库被保存为pickle,而gensimsave被使用_ As _ text方法将字典保存为txt
这是为了方便后续模块调用。如果将简单变量存储为变量,则需要大量内存,因此只能增加io的数量以确保数据安全。
语料库更新模块
输入每天新增的文件夹路径目录,提取文档后更新词典和语料库
def更新(self,new_dir):
如果os.path.存在('dictionary.txt'):
dictionary=corporate.dictionary。load_ from_ text('dictionary.txt')
否则:
打印('-----------尚未构建词典库---------')
回来

new_doc_name=os.listdir(new_dir)
使用open('doc.json','r',enco