当前位置:   article > 正文

【大数据管理】Python实现带位置的倒排索引_python倒排索引

python倒排索引

读取文本文件内容,根据内容构建 类型-书名 的倒排索引,文件内容如下

加分项:实现带位置的倒排索引
```
西游记 古典小说 浪漫主义
水浒传 古典小说 历史
三国演义 古典小说 历史
红高粱 现代小说 浪漫主义
史记 史书 历史 纪传体
资治通鉴 史书 历史 编年体
```

根据倒排索引实现某个标签的小说有哪些,例如查询所有古典小说,结果是西游记,水浒传,三国演义
 

倒排索引一般在大规模文档中使用以提高索引效率。在倒排索引中,每个词项都有一个记录出现该词项的所有文档的列表,该表中的每个元素记录的是词项在某文档中的一次出现信息,这个表中的每个元素通常称为倒排记录,每个词项对应的整个表称为倒排记录表,所有词项的倒排记录表一起构成全体倒排记录表。要建立倒排索引,首先要收集需要建立索引的文档,然后将每篇文档转换成一个个词条的列表,这个过程通常称为词条化;之后要进行语言学预处理,产生归一化的词条来作为词项;再对所有文档按照其中出现的词项来建立倒排索引,索引中包括一部词典和一个全体倒排记录表。

对于本题,我使用Python语言实现了带位置的倒排索引。首先获取dir文件夹下所有的txt文件,并将其存入file列表中;之后进行语言学的预处理,加载停用词,去除标点、数字等,将文本拆分成(词语,位置)的二元组形式,并将这些二元组存入word_list列表;之后建立一个词典inverted,其中key为词语,value为位置,循环所有文件建立最终的倒排索引,并将结果存入inverted.json中。

  1. import re, os, json
  2. """
  3. 建立带位置的倒排索引
  4. """
  5. # 从文件夹中获取文件
  6. def get_files(dir):
  7. files = []
  8. for file in os.listdir(dir):
  9. if file.endswith('txt'):
  10. files.append(file)
  11. return files
  12. #将文本拆分为(位置、单词)
  13. def word_split(text):
  14. stopwords = ['的', '了', '呢']
  15. word_list = []
  16. # 去除数字
  17. text = re.sub(pattern=r"\d", repl=r"", string=text)
  18. # 只包含单词和小写字母
  19. text = re.findall(r'\w+', text.lower())
  20. for index, word in enumerate(text):
  21. # 去除停用词
  22. if word not in stopwords:
  23. word_list.append((index, word))
  24. return word_list
  25. # 建立一个字典,词语作为key,位置作为value
  26. # 对一个文件
  27. def inverted_index_single(text):
  28. inverted = {}
  29. for index, word in text:
  30. locations = inverted.setdefault(word, [])
  31. locations.append(index)
  32. return inverted
  33. # 循环所有的文件建立最终的倒排索引
  34. def inverted_index_all(inverted, doc_id, doc_inverted):
  35. for word, locations in doc_inverted.items():
  36. indices = inverted.setdefault(word, {})
  37. indices[doc_id] = locations
  38. return inverted
  39. def inverted_index_from_folder(dir):
  40. # 得到文件
  41. files = get_files(dir)
  42. # 最终的倒排索引
  43. inverted_mul = {}
  44. for file in files:
  45. with open(dir + file, 'r') as myfile:
  46. # 字符串包含单个文件中的所有内容
  47. words = myfile.read().replace('\n', ' ')
  48. split_words = word_split(words)
  49. # 为单个文件创建反向索引
  50. inverted_single_file = inverted_index_single(split_words)
  51. # 创建最终的倒排索引
  52. inverted_index_all(inverted_mul, file, inverted_single_file)
  53. return inverted_mul
  54. #将倒排索引保存到json文件
  55. def save_index(inverted_index):
  56. with open('inverted_index.json', 'w') as fp:
  57. json.dump(inverted_index, fp,ensure_ascii=False)
  58. def main():
  59. inverted_index = inverted_index_from_folder("D:/books/")
  60. save_index(inverted_index)
  61. print("已将倒排索引结果存入inverted.json!")
  62. if __name__ == "__main__":
  63. main()

2f91f2edc5bc4404a85cfe899f3abb7e.png

08679f13e9e442d5be6cb80a0b1b3003.png

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小舞很执着/article/detail/839365
推荐阅读
相关标签
  

闽ICP备14008679号