LoginSignup
1
4

More than 1 year has passed since last update.

Windows環境のPythonでN-gram生成ツール SRILM を使う方法

Posted at

SRILMのインストール手順

1.SRILMのインストール

今回はCygwin環境にSRILMをインストールします。
Cygwinの設定は前回の記事(Windows環境のPythonで形態素解析器 -- ChaSen -- を使う方法)を参照

SRILMのダウンロードはこちらから(今回は srilm-1.7.3.tar.gz を使用しています。)

Cygwin64の直下に「srilm」というフォルダを作成

cd /
mkdir srilm
cd srilm

作成したフォルダにダウンロードしたsrilm-1.7.3.tar.gzをコピーする。
そして、作成したフォルダ内でsrilm-1.7.3.tar.gzを解凍する。

tar zxvf srilm-1.7.3.tar.gz

解凍したフォルダ内の「Makefile」を開き、次の行を見つける。

# SRILM = /home/speech/stolcke/project/srilm/devel

見つけた行を次のように書き換え、保存する。

SRILM = /srilm

Cygwinに戻り、次のように実行する。

make

2.SRILMの実行

ngram」や「ngram-count」の実行ファイルがあるフォルダに移動する。

cd bin/cygwin64/

次のように実行する。

./ngram-count -text [input_corpus] -lm [output_language_model] -order 3 -write [output_ngram]

input_corpus:入力するファイル(文章から単語をスペースで区切ったもの)
output_language_model:出力する言語モデルのファイル名
output_ngram:出力するN-gramのファイル名

コマンドプロンプトでSRILMを実行

環境変数の変更方法前回の記事(Windows環境のPythonで形態素解析器 -- ChaSen -- を使う方法)を参照

Windowsのコマンドプロンプトを開く。
次のように実行する。

C:\cygwin64\srilm\bin\cygwin64\ngram-count -text [input_corpus] -lm [output_language_model] -order 3 -write [output_ngram]

Cygwinの時と同じ結果が出力されればOK。

PythonでSRILMを実行

ソースコードを以下に載せております。

srilm.py
import subprocess
import os

def srilm(srilm_path, input_corpus, output_language_model, output_ngram):
    path = os.getcwd().replace(os.sep,'/')+"/" # 実行中のパス取得
    cmd = "{0} -text {1} -lm {2} -order 3 -write {3}".format(srilm_path, path+input_corpus, path+output_language_model, path+output_ngram)
    proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()

if __name__ == '__main__':
    srilm_path = "C:/cygwin64/srilm/bin/cygwin64/ngram-count"
    input_corpus = "corpus.txt"
    output_language_model = "lm.txt"
    output_ngram = "count.txt"

    srilm(srilm_path, input_corpus, output_language_model, output_ngram)

コマンドプロンプトで実行した時と同じ結果が出力されればOK。
以上、Windows環境のPythonでSRILMを使う方法でした。

参考にしたページ

1
4
0

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
1
4