LoginSignup
23

More than 1 year has passed since last update.

BERTでサクっと文章要約する

Last updated at Posted at 2021-04-10

はじめに

BERTを用いたテキスト要約のライブラリbert-extractive-summarizerを見つけたので試してみた。あたかも自分がサクッと作ったような書き方になってしまったが、実際はこのツールがサクっとやってくれたという話。

bert-extractive-summarizer とは

講義要約用のライブラリである。仕組みとしては、まず文章をエンベディングし、クラスタリングした後、重心に近い文章(クラスタを代表するもの)をピックアップしているようである。

講義用とは言え、他の文章にも色々使えそうである。
ちなみに本ライブラリは英語用であるが、自分は英語を要約したいのでこれで十分である。

インストール

pip install bert-extractive-summarizer

実際には、pytorch等いくつか依存するライブラリがあるので、試行錯誤しながら入れてみよう。

プログラム

コマンドラインで動かすプログラムを書いてみた。入力とするテキストファイル、出力ファイル、抽出文章の数を指定できる。

text_summarizer.py

import argparse
from summarizer import Summarizer


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-input", type=str, required=True)
    parser.add_argument("-num_sentences", type=int, default=5)
    parser.add_argument("-output", type=str, required=True)
    args = parser.parse_args()

    model = Summarizer()
    with open(args.input, "r", encoding="utf-8") as f:
        body = "".join(f.readlines())

    #print(body)
    result = model(body, num_sentences=args.num_sentences)
    full = ''.join(result)
    with open(args.output, "w", encoding='utf-8') as fw:
        fw.write(full)

if __name__ == "__main__":
    main()

動かしてみた

とりあえず、CNNの以下のニュースをやってみた。
https://edition.cnn.com/2021/04/10/sport/san-diego-padres-no-hitter-joe-musgrove/index.html

上の文章をinput.txtに保存して以下を実行。今回は3つの文章を抽出する。

$ python.exe text_summarizer.py -input input.txt -num_sentences 3 -output output.txt

結果は以下の通り

output.txt
Pitcher Joe Musgrove tossed the first no-hitter in Padres franchise history on 
Friday night, as San Diego defeated the Texas Rangers 3-0 at Globe Life Field in
Arlington, Texas. Musgrove struck out 10 and only allowed one base runner when 
he hit Joey Gallo, which prevented a perfect game. I looked up at the scoreboard 
to see what (the) pitch count was, and I was at, like, 67, and I was like, we've
 got some room to work with." Musgrove added, "It feels really good to be in a
 Padres uniform when I did it.

一応ノーヒットノーランを達成した様子が伝わってくる。

参考

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23