質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.48%
Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Mecab

Mecabは、オープンソースの形態素解析エンジンです。 言語、辞書、コーパスに依存しない汎用的な設計を基本方針としています。 Mecabの由来は、開発者の好物である和布蕪(めかぶ)から名づけられました。

Q&A

解決済

1回答

3894閲覧

Python3で呼び出されたMecabの結果をWebブラウザ上で表示させたい。

testcase

総合スコア18

Python 3.x

Python 3はPythonプログラミング言語の最新バージョンであり、2008年12月3日にリリースされました。

Mecab

Mecabは、オープンソースの形態素解析エンジンです。 言語、辞書、コーパスに依存しない汎用的な設計を基本方針としています。 Mecabの由来は、開発者の好物である和布蕪(めかぶ)から名づけられました。

0グッド

0クリップ

投稿2018/07/17 17:56

編集2018/07/29 18:39

お世話になります。

Python3

1#!/usr/bin/env python3.4 2# -*- coding: utf-8 -*- 3from natto import MeCab 4 5mc = MeCab() 6 7text = "おはようございます。" 8 9ma = mc.parse(text) 10 11print("Content-Type: text/html; charset=utf-8\n\n") 12print(""" 13<!DOCTYPE html> 14<html> 15<head> 16<meta charset="utf-8x"> 17<title>CGIスクリプト</title> 18</head> 19<body> 20<pre> 21""") 22print(ma) 23print(""" 24</pre> 25</body> 26</html> 27""") 28

このようなMecabの解析結果をWebブラウザ上で表示するプログラムを書きました。
ファイル名をsample.pyとでもすると、

Python3

1 % python3 sample.py

と入力すると以下のように表示してくれます。

Python3

1Content-Type: text/html; charset=utf-8 2 3 4<!DOCTYPE html> 5<html> 6<head> 7<meta charset="utf-8x"> 8<title>CGIスクリプト</title> 9</head> 10<body> 11<h1>CGIスクリプト</h1> 12<p>これはサーバの実行結果として生成されたHTMLです</p> 13<pre> 14 15おはよう 感動詞,*,*,*,*,*,おはよう,オハヨウ,オハヨー 16ござい 助動詞,*,*,*,五段・ラ行特殊,連用形,ござる,ゴザイ,ゴザイ 17ます 助動詞,*,*,*,特殊・マス,基本形,ます,マス,マス 18。 記号,句点,*,*,*,*,。,。,。 19EOS 20 21</pre> 22</body> 23</html> 24

この結果を、できれば http://hoge.com/sample.pyなどと書いてWebブラウザ上で表示させたいと考えているのですが、上手く表示されません。
サーバはXserverを利用しています。

.htaccessでの設定がおかしいのかと考えましたが、

Python3

1#!/usr/bin/env python3 2 3import datetime 4 5#フォーマット文字列の作成 6html_body = """ 7<html><body> 8{0.year:d}/{0.month:d}/{0.day:d} {0.hour:d}:{0.minute:d}:{0.second:d} 9</body></html>""" 10 11now=datetime.datetime.now() 12 13print("Content-type: text/html\n") 14print(html_body.format(now))

等も作りましたが、こちらは結果がブラウザ上にきちんと表示されます。
.htaccessはこのように設定しています。

AddHandler cgi-script .py

どのようにすればいいのかご教授いただけますと幸甚です。
よろしくおねがいします。

その後、以下の事柄を試しました。

Python3

1#!/usr/bin/env python3.4 2# -*- coding: utf-8 -*- 3 4import sys 5import io 6sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 7#sys.stdout.write('Content-type: text/html; charset=UTF-8\n\n') 8 9import cgi 10# enable debugging 11import cgitb 12cgitb.enable() 13 14from natto import MeCab 15 16#mc = MeCab.Tagger('-Ochasen') 17 18text = "おはようございます。" 19 20#ma = mc.parse(text) 21 22print("Content-Type: text/html; charset=utf-8\n\n") 23print(""" 24<!DOCTYPE html> 25<html> 26<head> 27<meta charset="utf-8x"> 28<title>CGIスクリプト</title> 29</head> 30<body> 31<pre> 32""") 33#print(ma) 34print(text) 35print(""" 36</pre> 37</body> 38</html> 39""")

このようにすることで、少なくとも文字コードはUTF-8に統一され、
Mecabを利用しない範囲においては、表示されるようにはなりました。
まだMecabについては上手く表示ができておりませんので、
引き続き試していきたいと思います。

その後、この直上のプログラムで、コメント記号を外した

Python3

1mc = MeCab.Tagger('-Ochasen')

は、コマンドライン上での実行と併せて

Python3

1mc = MeCab()

とした方がよいことがわかりました。
しかし、コメント記号を外すと
いずれでも500 internal Server Errorとなります。
ちなみに、このmcをprint文で表示させると、

Python3

1<natto.mecab.MeCab model=<cdata 'mecab_model_t *' 0x55f5d313c190>, 2 tagger=<cdata 'mecab_t *' 0x55f5d31dc950>, 3 lattice=<cdata 'mecab_lattice_t *' 0x55f5d31463a0>, 4 libpath="/home/.../bin/mecab/lib/libmecab.so", 5 options={}, 6 dicts=[<natto.dictionary.DictionaryInfo dictionary= 7 <cdata 'mecab_dictionary_info_t *' 0x55f5d3133660>, 8 filepath="/home/.../bin/mecab/lib/mecab/dic/ipadic/sys.dic", 9 charset=utf-8, type=0>], 10 version=0.996>

このようになります。
引き続き調査します。
よろしくお願いします。

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

hayataka2049

2018/07/17 18:02

「上手く表示されません」が具体的にどのような状況なのか教えてください。また、 python3 sample.pyはどこで実行していますか?
hayataka2049

2018/07/17 18:03

あと、エラーログを探してみてください
KojiDoi

2018/07/17 18:08

pythonではなくサーバ設定の問題でしょう。 Xserverではnginx使っているようですから、"nginx cgi 設置" などググって見てはどうでしょう。
testcase

2018/07/17 18:23

ありがとうございます。500と返ってきます。エラーログですが、「End of script output before headers: sample.py」と出ます。public_html内でPython関連のディレクトリを作成し、その中で実行しています。nginxってそんな状況なのですね。ありがとうございます。調べてみます。
testcase

2018/07/19 12:48

FCGIについて調べました。fcgiwrapをインストールしようと考え、git cloneでダウンロードしてからautoreconfした後、configureすると、checking for 「FCGX_Init in -lfcgi... no」となって、configureできませんでした。これにつきましてご教示いただけませんでしょうか?よろしくお願いします。
guest

回答1

0

ベストアンサー

ずっと内部エラーのままじゃしょうがないので、とりあえずtracebackでも見てみませんか。

python

1#!/usr/bin/env python3.4 2# -*- coding: utf-8 -*- 3 4import sys 5import io 6sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') 7#sys.stdout.write('Content-type: text/html; charset=UTF-8\n\n') 8 9import cgi 10# enable debugging 11import cgitb 12cgitb.enable() 13 14from natto import MeCab 15import traceback 16 17 18 19text = "おはようございます。" 20 21try: 22 mc = MeCab.Tagger('-Ochasen') 23 ma = mc.parse(text) 24except: 25 traceback_txt = traceback.format_exc() 26 27print("Content-Type: text/html; charset=utf-8\n\n") 28print(""" 29<!DOCTYPE html> 30<html> 31<head> 32<meta charset="utf-8x"> 33<title>CGIスクリプト</title> 34</head> 35<body> 36<pre> 37""") 38#print(ma) 39print(text) 40print(traceback_txt) 41print(""" 42</pre> 43</body> 44</html> 45""")

投稿2018/07/30 06:33

hayataka2049

総合スコア30933

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

testcase

2018/07/30 13:25 編集

ありがとうございます。 少し修正して以下のようにしてみました。 ```Python #!/usr/bin/env python3.4 # -*- coding: utf-8 -*- import logging import traceback import sys import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8') import cgi # enable debugging import cgitb cgitb.enable() from natto import MeCab text = "おはようございます。" try: mc = MeCab() ma = mc.parse(text) except Exception as e: logging.error(traceback.format_exc()) #traceback.print_exc() print("Content-type: text/html; charset=utf-8\n\n") #print() print(""" <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>CGIスクリプト</title> </head> <body> <h1>CGIスクリプト</h1> <p>これはサーバの実行結果として生成されたHTMLです</p> <pre> """) print(ma) print(text) print(""" </pre> </body> </html> """) ``` この結果、MeCabの処理はError Catchされており、 結果としてブラウザ上で maなんて変数は未定義ですよと言われてしまいました。 ```Python NameError Python 3.4.5: /usr/bin/python3.4 Mon Jul 30 22:21:38 2018 A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred. /home/.../public_html/python/sample1.py in () 53 """) 54 #print(mc) => 55 print(ma) 56 print(text) 57 #print(sys.version) builtin print = <built-in function print>, ma undefined NameError: name 'ma' is not defined args = ("name 'ma' is not defined",) with_traceback = <built-in method with_traceback of NameError object> ```
testcase

2018/07/30 13:28

上記のmaのエラーはその後tryの前で ma = "" などとすればエラーはなくなりました。
hayataka2049

2018/07/30 13:32

私の回答どおりにするとどうなりますか?
testcase

2018/07/30 14:50

このような感じになりました。 Content-Type: text/html; charset=utf-8 <!DOCTYPE html> <html> <head> <meta charset="utf-8x"> <title>CGIスクリプト</title> </head> <body> <pre> おはようございます。 <!--: spam Content-Type: text/html <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> <body bgcolor="#f0f0f8"><font color="#f0f0f8" size="-5"> --> --> </font> </font> </font> </script> </object> </blockquote> </pre> </table> </table> </table> </table> </table> </font> </font> </font><body bgcolor="#f0f0f8"> <table width="100%" cellspacing=0 cellpadding=2 border=0 summary="heading"> <tr bgcolor="#6622aa"> <td valign=bottom>&nbsp;<br> <font color="#ffffff" face="helvetica, arial">&nbsp;<br><big><big><strong>NameError</strong></big></big></font></td ><td align=right valign=bottom ><font color="#ffffff" face="helvetica, arial">Python 3.6.5: /home/.../.pyenv/versions/anaconda3-5.2.0/bin/python3<br>Mon Jul 30 23:45:29 2018</font></td></tr></table> <p>A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.</p> <table width="100%" cellspacing=0 cellpadding=0 border=0> <tr><td bgcolor="#d8bbff"><big>&nbsp;</big><a href="file:///home/.../h2o.jp/public_html/python/sample2.py">/home/.../h2o.jp/public_html/python/sample2.py</a> in <strong><module></strong>()</td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;&nbsp;&nbsp;39</small>&nbsp;#print(ma)<br> </tt></font></td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;&nbsp;&nbsp;40</small>&nbsp;print(text)<br> </tt></font></td></tr> <tr><td bgcolor="#ffccee"><tt>=&gt;<small>&nbsp;&nbsp;&nbsp;41</small>&nbsp;print(traceback_txt)<br> </tt></td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;&nbsp;&nbsp;42</small>&nbsp;print("""<br> </tt></font></td></tr> <tr><td><font color="#909090"><tt>&nbsp;&nbsp;<small>&nbsp;&nbsp;&nbsp;43</small>&nbsp;&lt;/pre&gt;<br> </tt></font></td></tr> <tr><td><small><font color="#909090"><em>builtin</em> <strong>print</strong>&nbsp;= &lt;built-in function print&gt;, traceback_txt <em>undefined</em></font></small></td></tr></table><p><strong>NameError</strong>: name 'traceback_txt' is not defined <br><tt><small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</small>&nbsp;</tt>args&nbsp;= ("name 'traceback_txt' is not defined",) <br><tt><small>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</small>&nbsp;</tt>with_traceback&nbsp;= &lt;built-in method with_traceback of NameError object&gt; <!-- The above is a description of an error in a Python program, formatted for a Web browser because the 'cgitb' module was enabled. In case you are not reading this in a Web browser, here is the original traceback: Traceback (most recent call last): File "sample2.py", line 41, in &lt;module&gt; print(traceback_txt) NameError: name 'traceback_txt' is not defined -->
hayataka2049

2018/07/30 14:58

妙ですね。except節に行ってないか、行っているけど代入できていない?
testcase

2018/07/30 16:06

申し訳ありません。 755の権限が抜けておりました。 ターミナルでの実行ですと、このようになります。↓ Content-Type: text/html; charset=utf-8 <!DOCTYPE html> <html> <head> <meta charset="utf-8x"> <title>CGIスクリプト</title> </head> <body> <pre> おはようございます。 Traceback (most recent call last): File "sample3.py", line 22, in <module> mc = MeCab.Tagger('-Ochasen') AttributeError: type object 'MeCab' has no attribute 'Tagger' </pre> </body> </html> ブラウザ上ですとこのようになります。↓ おはようございます。 Traceback (most recent call last): File "sample3.py", line 22, in mc = MeCab.Tagger('-Ochasen') AttributeError: type object 'MeCab' has no attribute 'Tagger'
testcase

2018/08/02 15:32

引き続きこのようになりました。 #!/usr/bin/env python3.4 # -*- coding: utf-8 -*- import sys import io sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8') import cgi # enable debugging import cgitb cgitb.enable() from natto import MeCab import traceback text = "おはようございます。" traceback_txt = "" ma = "" try: mc = MeCab() ma = mc.parse(text) except: #traceback_txt = logging.error(traceback.format_exc()) traceback_txt = traceback.format_exc() ma = "形態素解析できませんでした。" #print("Content-Type: text/html; charset=utf-8\n\n") print("Content-Type: text/html; charset=utf8\n") print(""" <!DOCTYPE html> <html> <head> <meta charset="utf8"> <title>CGIスクリプト</title> </head> <body> <pre> """) print(text) print(ma) print(traceback_txt) print(""" </pre> </body> </html> """) このソースですと、ターミナル上では形態素解析ができますが、 ブラウザで表示させると以下のようになります。 おはようございます。 形態素解析できませんでした。 Traceback (most recent call last): File "/home/trombone/.local/lib/python3.4/site-packages/natto/environment.py", line 144, in __get_libpath res = Popen(cmd, stdout=PIPE).communicate() File "/usr/lib64/python3.4/subprocess.py", line 856, in __init__ restore_signals, start_new_session) File "/usr/lib64/python3.4/subprocess.py", line 1460, in _execute_child raise child_exception_type(errno_num, err_msg) FileNotFoundError: [Errno 2] No such file or directory: 'mecab-config' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/trombone/.local/lib/python3.4/site-packages/natto/mecab.py", line 147, in __init__ env = MeCabEnv(**kwargs) File "/home/trombone/.local/lib/python3.4/site-packages/natto/environment.py", line 53, in __init__ self.libpath = self.__get_libpath() File "/home/trombone/.local/lib/python3.4/site-packages/natto/environment.py", line 155, in __get_libpath raise EnvironmentError(self._ERROR_NOLIB.format(lib)) OSError: libmecab.so could not be found, please use MECAB_PATH During handling of the above exception, another exception occurred: Traceback (most recent call last): File "sample21.py", line 26, in mc = MeCab() File "/home/trombone/.local/lib/python3.4/site-packages/natto/mecab.py", line 222, in __init__ raise MeCabError(err) natto.api.MeCabError: libmecab.so could not be found, please use MECAB_PATH 引き続き調べてみます。
hayataka2049

2018/08/02 16:15

CGIからパスとか環境変数とかあたりが見えてない結果な気がするので、その線でいろいろあたってみるべきかと
testcase

2018/08/02 16:36

ありがとうございます。 以下のようにできました! おはようございます。 おはよう 感動詞,*,*,*,*,*,おはよう,オハヨウ,オハヨー ござい 助動詞,*,*,*,五段・ラ行特殊,連用形,ござる,ゴザイ,ゴザイ ます 助動詞,*,*,*,特殊・マス,基本形,ます,マス,マス 。 記号,句点,*,*,*,*,。,。,。 EOS 最初、import osした際に, osでのpathの値をそのまま使えばいけると思い込んでいましたので、 上手く表示できない際には、osライブラリは使えないのかと勘違いしてました。 import os os.environ['MECAB_PATH'] = '/home/.../bin/mecab/lib/libmecab.so' os.environ['MECAB_CHARSET'] = 'utf8' と、こんな感じで書いてやる必要があったということでした。 どうもありがとうございました!
hayataka2049

2018/08/02 16:43 編集

natto-pyのreadmeとかでそうしろって書いてあるんですか・・・ なんでそれで行けるのかわからない(汗)なんかwebサーバ側でごにょごにょしないとダメかなぁ、とか思ってたんですが あと、ずいぶんナイーブなCGIですが、これから拡張していくならセキュリティとか気をつけてくださいね(ユーザの入力を受け取って~とかやりだすと色々考えるべきことが多いですね)。実験目的で、すぐ潰す予定のページとかならそこまでシビアに考える必要はないかもですけど
testcase

2018/08/07 01:58

お返事が遅くなりまして申し訳ありません。 そうですね、とりあえずは技術獲得のレベルですので、このままでは怖いですね。 またよろしくお願いいたします。 お忙しい中ありがとうございました。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.48%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問