defbuild_invert_index(docs: list[str]) -> dict[str, list[int]]: invert_index: dict[list[int]] = defaultdict(list) for doc in docs: words = jieba.cut_for_search(doc) for word in words: invert_index[word].append(docs.index(doc)) return invert_index
defretrive(query: str, inverted_index: dict[str, list[int]]) -> list[int]: words = jieba.cut_for_search(query) result = set() for word in words: if word in inverted_index: result.update(inverted_index[word]) returnlist(result)
if __name__ == "__main__": invert_index = build_invert_index(forward_index)
whileTrue: query = input("请输入查询词:") if query == "q": break result = retrive(query, invert_index) print(f"查询词:{query}的结果为:") for doc in result: print(forward_index[doc])