当前位置:   article > 正文

自然语言处理实战项目4-文本相似度的搜索功能,搜索文本内容_文档相同之处查询

文档相同之处查询

大家好,我是微学AI,今天给大家带来自然语言处理实战项目4-文本相似度的搜索功能,搜索文本内容。文本相似度搜索是一种基于自然语言处理技术,用于搜索和匹配文本内容的方法。其主要目的是将用户输入的查询内容与已有的文本数据进行比较,并找到最相似的文本数据。

本文本以目标实现为导向,实战让大家跑通文本相似度的搜索功能。

一、实现文本相似度的搜索功能步骤:

1.首先加载与处理文件夹数据,本文以txt文件为例子,批量处理。

2.然后构建文件名和文件内容的索引文件。

3.在进行文档向量化与模型构建,生成向量模型

4.加载模型进行相似度的计算并返回。

5.后续可以新增文档到向量模型,可搜索到新加的文件

、文本相似度的搜索功能代码:

1.构建文件搜索引擎类

  1. import os
  2. from sklearn.feature_extraction.text import TfidfVectorizer
  3. from sklearn.metrics.pairwise import cosine_similarity
  4. import pickle
  5. from settings.app_config import project_config as fileconfig
  6. import PyPDF2
  7. import csv
  8. index_file = 'index.pkl'
  9. vectorizer_file = 'vectorizer.pkl'
  10. index_file_path = 'file_path.pickle'
  11. # 构建文件搜索引擎类
  12. class FileSearchManage():
  13. def __init__(self):
  14. self.index_file_path = index_file_path
  15. self.index_file = index_file
  16. self.vectorizer_file = vectorizer_file
  17. #读取文件
  18. def read_files(self,folder_path):
  19. files_data = {}
  20. for file_name in os.listdir(folder_path):
  21. if file_name.endswith(".txt"):
  22. with open(os.path.join(folder_path, file_name), 'r', encoding='utf-8') as f:
  23. files_data[file_name] = f.read().replace('\n', '')
  24. return files_data
  25. # 保存 csv 文件
  26. def save_csv_files(self, folder_path,csv_path):
  27. # 将信息写入csv文件
  28. with open(csv_path, 'w', newline='', encoding='utf-8') as csvfile:
  29. fieldnames = ['file_name', 'paragraph', 'content']
  30. writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
  31. writer.writeheader()
  32. for file_name in os.listdir(folder_path):
  33. if file_name.endswith(".pdf"):
  34. path_name, paragraph = ocr_paragraph_pdf(os.path.join(folder_path, file_name))
  35. for i, pa in enumerate(paragraph):
  36. pa = pa.replace('\n', '').replace(' ', '')
  37. if len(pa) > 4:
  38. writer.writerow({'file_name': file_name,
  39. 'paragraph': i,
  40. 'content': pa})
  41. # 读取pickle索引文件
  42. def read_pickle(self,index_file_path):
  43. with open(index_file_path, 'rb') as f:
  44. index = pickle.load(f)
  45. return index
  46. #分词、去除停用词 处理
  47. def preprocess_data(self,files_data):
  48. processed_data = {}
  49. for file_name, content in files_data.items():
  50. # 在这里可以对文档内容进行预处理(例如:分词、去除停用词)
  51. processed_data[file_name] = content
  52. return processed_data
  53. # 创建索引文件向量
  54. def create_tfidf_index(self,processed_data):
  55. vectorizer = TfidfVectorizer()
  56. corpus = list(processed_data.values())
  57. X = vectorizer.fit_transform(corpus)
  58. return X, vectorizer
  59. # 报错文件json
  60. def save_file(self,index_file_path,files_data):
  61. with open(index_file_path, 'wb') as f:
  62. pickle.dump(files_data, f)
  63. # 保存索引文件向量
  64. def save_index(self,index, vectorizer, index_file, vectorizer_file):
  65. with open(index_file, 'wb') as f:
  66. pickle.dump(index, f)
  67. with open(vectorizer_file, 'wb') as f:
  68. pickle.dump(vectorizer, f)
  69. # 加载索引文件向量
  70. def load_index(self,index_file, vectorizer_file):
  71. with open(index_file, 'rb') as f:
  72. index = pickle.load(f)
  73. with open(vectorizer_file, 'rb') as f:
  74. vectorizer = pickle.load(f)
  75. return index, vectorizer
  76. def preprocess_query(self,query):
  77. # 对查询进行预处理(例如:分词、去除停用词)
  78. return query
  79. # 文件查找函数
  80. def search(self,query, index, vectorizer, files_data,num):
  81. processed_query = self.preprocess_query(query)
  82. query_vector = vectorizer.transform([processed_query])
  83. cosine_similarities = cosine_similarity(index, query_vector)
  84. top_file_indices = cosine_similarities.ravel().argsort()[-int(num):][::-1]
  85. # print(top_file_indices)
  86. results = []
  87. for file_index in top_file_indices:
  88. file_name = list(files_data.keys())[file_index]
  89. file_content = files_data[file_name]
  90. similarity = cosine_similarities[file_index][0]
  91. results.append((file_name, file_content, similarity))
  92. return sorted(results, key=lambda x: x[-1], reverse=True)
  93. # return most_similar_file_name, most_similar_file_content
  94. # 文件相似度计算
  95. def search_similar_files(self,query,num):
  96. files_data = self.read_pickle(self.index_file_path)
  97. #processed_data = self.preprocess_data(files_data)
  98. index, vectorizer = self.load_index(self.index_file, self.vectorizer_file)
  99. result = self.search(query, index, vectorizer, files_data,num)
  100. result = [x[0]+" "+str(x[2]) for x in result]
  101. return result
  102. # print('File content:', result_file_content)
  103. # 获取文件内容
  104. def get_content(self,filename):
  105. files_data = self.read_pickle(self.index_file_path)
  106. result = files_data[filename]
  107. return result
  108. # 新增新的索引文件
  109. def add_new_file(self,file_path):
  110. index,vectorizer = self.load_index(self.index_file, self.vectorizer_file)
  111. files_data = self.read_pickle(self.index_file_path)
  112. content =''
  113. try:
  114. if file_path.split('.')[-1]=='txt':
  115. with open(file_path, 'r', encoding='utf-8') as f:
  116. file_content = f.read().replace('\n', '')
  117. files_data[file_path.split('/')[-1]] = file_content
  118. if file_path.split('.')[-1] == 'pdf':
  119. with open(file_path, 'rb') as f:
  120. pdf_reader = PyPDF2.PdfFileReader(f)
  121. # 获取PDF文件的页数
  122. num_pages = pdf_reader.numPages
  123. # 创建文本文件,并将PDF文件每一页的内容写入
  124. for i in range(num_pages):
  125. page = pdf_reader.getPage(i)
  126. text = page.extractText().replace(' ', '')
  127. content = content + text
  128. file_content = content.replace('\n', '')
  129. files_data[file_path.split('/')[-1]] = file_content
  130. with open(self.index_file_path, 'wb') as f:
  131. pickle.dump(files_data, f)
  132. corpus = list(files_data.values())
  133. X = vectorizer.fit_transform(corpus)
  134. with open(self.index_file, 'wb') as f:
  135. pickle.dump(X, f)
  136. with open(self.vectorizer_file, 'wb') as f:
  137. pickle.dump(vectorizer, f)
  138. return 'successful'
  139. except Exception as e:
  140. print(e)
  141. return 'fail'

2.构建文件夹导入函数

  1. if __name__ == '__main__':
  2. folder_path = '文件夹的地址' # 例如'E:/data'
  3. def create_file(folder_path):
  4. FileSearch = FileSearchManage()
  5. files_data = FileSearch.read_files(folder_path)
  6. processed_data = FileSearch.preprocess_data(files_data)
  7. FileSearch.save_file(index_file_path,processed_data)
  8. index, vectorizer = FileSearch.create_tfidf_index(processed_data)
  9. FileSearch.save_index(index, vectorizer, index_file, vectorizer_file)
  10. def file_search(query):
  11. FileSearch = FileSearchManage()
  12. files_data = FileSearch.read_pickle(index_file_path)
  13. processed_data = FileSearch.preprocess_data(files_data)
  14. index, vectorizer = FileSearch.load_index(index_file, vectorizer_file)
  15. result_file_name = FileSearch.search(query, index, vectorizer, files_data,num=5)
  16. print('File name:', result_file_name)
  17. def file_add(folder_path):
  18. FileSearch = FileSearchManage()
  19. files_data = FileSearch.read_pdf_files(folder_path)
  20. with open(index_file_path, 'wb') as f:
  21. pickle.dump(files_data, f)
  22. processed_data = FileSearch.preprocess_data(files_data)
  23. index, vectorizer = FileSearch.create_tfidf_index(processed_data)
  24. FileSearch.save_index(index, vectorizer, index_file, vectorizer_file)
  25. index, vectorizer = FileSearch.load_index(index_file, vectorizer_file)
  26. query = '*****'
  27. result_file_name = FileSearch.search(query, index, vectorizer, files_data,num=5)
  28. create_file(folder_path)
  29. #query ='搜索语句'
  30. #file_search(query)
  31. #file_add(folder_path)

我们还可以根据自己的需求,添加新的文件,可以是txt,pdf的文件,pdf有的文件可以直接转文本,有的图片的需要OCR识别,这个可以接入OCR进行识别,使得系统更加的完善。欢迎大家进行关注与支持,有更多需求和合作的可以联系。

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号