1. import re
    2. class SearchEngineBase(object):
    3. def __init__(self):
    4. pass
    5. def add_corpus(self, file_path):
    6. with open(file_path, 'r') as fin:
    7. text = fin.read()
    8. self.process_corpus(file_path, text)
    9. def process_corpus(self, id, text):
    10. raise Exception('process_corpus not implemented.')
    11. def search(self, query):
    12. raise Exception('search not implemented.')
    13. import re
    14. class BOWInvertedIndexEngine(SearchEngineBase):
    15. def __init__(self):
    16. super(BOWInvertedIndexEngine, self).__init__()
    17. self.inverted_index = {}
    18. def print_all (self):
    19. print(self.inverted_index['and'])
    20. def process_corpus(self, id, text):
    21. words = self.parse_text_to_words(text)
    22. for word in words:
    23. if word not in self.inverted_index:
    24. self.inverted_index[word] = []
    25. self.inverted_index[word].append(id)
    26. def search(self, query):
    27. query_words = list(self.parse_text_to_words(query))
    28. query_words_index = list()
    29. for query_word in query_words:
    30. query_words_index.append(0)
    31. # 如果某一个查询单词的倒序索引为空,我们就立刻返回
    32. for query_word in query_words:
    33. if query_word not in self.inverted_index:
    34. return []
    35. result = []
    36. while True:
    37. # 首先,获得当前状态下所有倒序索引的 index
    38. current_ids = []
    39. for idx, query_word in enumerate(query_words):
    40. current_index = query_words_index[idx]
    41. current_inverted_list = self.inverted_index[query_word]
    42. # 已经遍历到了某一个倒序索引的末尾,结束 search
    43. print(current_index)
    44. print(current_inverted_list)
    45. if current_index >= len(current_inverted_list):
    46. return result
    47. current_ids.append(current_inverted_list[current_index])
    48. print(query_words_index)
    49. print('current_ids:')
    50. print(current_ids)
    51. # 然后,如果 current_ids 的所有元素都一样,那么表明这个单词在这个元素对应的文档中都出现了
    52. if all(x == current_ids[0] for x in current_ids):
    53. print('x:')
    54. result.append(current_ids[0])
    55. query_words_index = [x + 1 for x in query_words_index]
    56. continue
    57. # 如果不是,我们就把最小的元素加一
    58. min_val = min(current_ids)
    59. min_val_pos = current_ids.index(min_val)
    60. query_words_index[min_val_pos] += 1
    61. @staticmethod
    62. def parse_text_to_words(text):
    63. # 使用正则表达式去除标点符号和换行符
    64. text = re.sub(r'[^\w ]', ' ', text)
    65. # 转为小写
    66. text = text.lower()
    67. # 生成所有单词的列表
    68. word_list = text.split(' ')
    69. # 去除空白单词
    70. word_list = filter(None, word_list)
    71. # 返回单词的 set
    72. return set(word_list)
    73. def main(search_engine):
    74. for file_path in ['1.txt', '2.txt', '3.txt', '4.txt', '5.txt']:
    75. search_engine.add_corpus(file_path)
    76. search_engine.print_all()
    77. while True:
    78. query = input()
    79. results = search_engine.search(query)
    80. print('found {} result(s):'.format(len(results)))
    81. for result in results:
    82. print(result)
    83. search_engine = BOWInvertedIndexEngine()
    84. 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。