開発環境
ライブラリのインストール
以下のドキュメントにあるようにインストールをします
pip install rank_bm25
ドキュメントから関連文の抽出
まずはいくつかの文章をindexにします
from rank_bm25 import BM25Okapi corpus = [ "Hello there good man!", "It is quite windy in London", "How is the weather today?" ] tokenized_corpus = [doc.split(" ") for doc in corpus] bm25 = BM25Okapi(tokenized_corpus)
次に 指定した文に近いものを探します
query = "windy London" tokenized_query = query.split(" ") doc_scores = bm25.get_scores(tokenized_query) print(doc_scores) token_n = bm25.get_top_n(tokenized_query, corpus, n=1) print(token_n)
結果は以下のように返ってきます
[0. 0.93729472 0. ] ['It is quite windy in London']