赞
踩
读取文本文件内容,根据内容构建 类型-书名 的倒排索引,文件内容如下
加分项:实现带位置的倒排索引
```
西游记 古典小说 浪漫主义
水浒传 古典小说 历史
三国演义 古典小说 历史
红高粱 现代小说 浪漫主义
史记 史书 历史 纪传体
资治通鉴 史书 历史 编年体
```
根据倒排索引实现某个标签的小说有哪些,例如查询所有古典小说,结果是西游记,水浒传,三国演义
倒排索引一般在大规模文档中使用以提高索引效率。在倒排索引中,每个词项都有一个记录出现该词项的所有文档的列表,该表中的每个元素记录的是词项在某文档中的一次出现信息,这个表中的每个元素通常称为倒排记录,每个词项对应的整个表称为倒排记录表,所有词项的倒排记录表一起构成全体倒排记录表。要建立倒排索引,首先要收集需要建立索引的文档,然后将每篇文档转换成一个个词条的列表,这个过程通常称为词条化;之后要进行语言学预处理,产生归一化的词条来作为词项;再对所有文档按照其中出现的词项来建立倒排索引,索引中包括一部词典和一个全体倒排记录表。
对于本题,我使用Python语言实现了带位置的倒排索引。首先获取dir文件夹下所有的txt文件,并将其存入file列表中;之后进行语言学的预处理,加载停用词,去除标点、数字等,将文本拆分成(词语,位置)的二元组形式,并将这些二元组存入word_list列表;之后建立一个词典inverted,其中key为词语,value为位置,循环所有文件建立最终的倒排索引,并将结果存入inverted.json中。
- import re, os, json
- """
- 建立带位置的倒排索引
- """
- # 从文件夹中获取文件
- def get_files(dir):
- files = []
- for file in os.listdir(dir):
- if file.endswith('txt'):
- files.append(file)
- return files
-
- #将文本拆分为(位置、单词)
- def word_split(text):
- stopwords = ['的', '了', '呢']
- word_list = []
- # 去除数字
- text = re.sub(pattern=r"\d", repl=r"", string=text)
- # 只包含单词和小写字母
- text = re.findall(r'\w+', text.lower())
- for index, word in enumerate(text):
- # 去除停用词
- if word not in stopwords:
- word_list.append((index, word))
- return word_list
-
- # 建立一个字典,词语作为key,位置作为value
- # 对一个文件
- def inverted_index_single(text):
- inverted = {}
- for index, word in text:
- locations = inverted.setdefault(word, [])
- locations.append(index)
- return inverted
-
- # 循环所有的文件建立最终的倒排索引
- def inverted_index_all(inverted, doc_id, doc_inverted):
- for word, locations in doc_inverted.items():
- indices = inverted.setdefault(word, {})
- indices[doc_id] = locations
- return inverted
-
- def inverted_index_from_folder(dir):
- # 得到文件
- files = get_files(dir)
- # 最终的倒排索引
- inverted_mul = {}
- for file in files:
- with open(dir + file, 'r') as myfile:
- # 字符串包含单个文件中的所有内容
- words = myfile.read().replace('\n', ' ')
- split_words = word_split(words)
- # 为单个文件创建反向索引
- inverted_single_file = inverted_index_single(split_words)
- # 创建最终的倒排索引
- inverted_index_all(inverted_mul, file, inverted_single_file)
-
- return inverted_mul
-
- #将倒排索引保存到json文件
- def save_index(inverted_index):
- with open('inverted_index.json', 'w') as fp:
- json.dump(inverted_index, fp,ensure_ascii=False)
-
- def main():
-
- inverted_index = inverted_index_from_folder("D:/books/")
- save_index(inverted_index)
-
- print("已将倒排索引结果存入inverted.json!")
-
- if __name__ == "__main__":
- main()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。