import reclass SearchEngineBase(object):def __init__(self):passdef add_corpus(self, file_path):with open(file_path, 'r') as fin:text = fin.read()self.process_corpus(file_path, text)def process_corpus(self, id, text):raise Exception('process_corpus not implemented.')def search(self, query):raise Exception('search not implemented.')import reclass BOWInvertedIndexEngine(SearchEngineBase):def __init__(self):super(BOWInvertedIndexEngine, self).__init__()self.inverted_index = {}def print_all (self):print(self.inverted_index['and'])def process_corpus(self, id, text):words = self.parse_text_to_words(text)for word in words:if word not in self.inverted_index:self.inverted_index[word] = []self.inverted_index[word].append(id)def search(self, query):query_words = list(self.parse_text_to_words(query))query_words_index = list()for query_word in query_words:query_words_index.append(0)# 如果某一个查询单词的倒序索引为空,我们就立刻返回for query_word in query_words:if query_word not in self.inverted_index:return []result = []while True:# 首先,获得当前状态下所有倒序索引的 indexcurrent_ids = []for idx, query_word in enumerate(query_words):current_index = query_words_index[idx]current_inverted_list = self.inverted_index[query_word]# 已经遍历到了某一个倒序索引的末尾,结束 searchprint(current_index)print(current_inverted_list)if current_index >= len(current_inverted_list):return resultcurrent_ids.append(current_inverted_list[current_index])print(query_words_index)print('current_ids:')print(current_ids)# 然后,如果 current_ids 的所有元素都一样,那么表明这个单词在这个元素对应的文档中都出现了if all(x == current_ids[0] for x in current_ids):print('x:')result.append(current_ids[0])query_words_index = [x + 1 for x in query_words_index]continue# 如果不是,我们就把最小的元素加一min_val = min(current_ids)min_val_pos = current_ids.index(min_val)query_words_index[min_val_pos] += 1@staticmethoddef parse_text_to_words(text):# 使用正则表达式去除标点符号和换行符text = re.sub(r'[^\w ]', ' ', text)# 转为小写text = text.lower()# 生成所有单词的列表word_list = text.split(' ')# 去除空白单词word_list = filter(None, word_list)# 返回单词的 setreturn set(word_list)def main(search_engine):for file_path in ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt']:search_engine.add_corpus(file_path)search_engine.print_all()while True:query = input()results = search_engine.search(query)print('found {} result(s):'.format(len(results)))for result in results:print(result)search_engine = BOWInvertedIndexEngine()main(search_engine)
对于BOW的难点,其实认真想一下画面就能理解:
比如输入 “word_1 word_2“ : 这两个词在第一次for循环,都能在1.txt中找到,所以current_ids 中有有两个1.txt -> (1.txt, 1.txt),直接加入result,因为他们都存在于同一个文档。
(下面我们需要判断这两个词是否继续存在与其他剩余文档)
我们先将query_words_index每个元素+1,是因为我们不再考虑1.txt了,而是考虑2.txt,3.txt等等剩余文档。
如果 word_1 通过查找发现存在2.txt中,但是word_2存在3.txt,current_ids 中的元素都不同 -> (2.txt, 3.txt )。所以我们进行“# 如果不是,我们就把最小的元素加一”注释后的代码,其中min(2.txt, 3.txt) = 2.txt, 我们把最小的txt序号+1,就代表我们不考虑2.txt,直接让word_1到3.txt中查找如果存在的话。
返回的判断条件就是txt序号+1过后的大小已经大于这个单词存在的文档数量了,直接返回result。
