1

マルコフ連鎖を使って〇〇っぽい文章を自動生成してみた

上記サイトを参考に、マルコフ解析と形態素解析を使い適当なテキストファイルを与えたらそれを材料に自動で文章を生成するものを作りたく、python3.7.2、mecab-0.996.exeをインストールした後コマンドプロンプトで learn.py を実行したところこのようなエラーが出ました。

C:\Users\Desktop>python learn.py

Traceback (most recent call last):
  File "learn.py", line 98, in <module>
    main()
  File "learn.py", line 84, in main
    print(''.join(sentence.split()))    # need to concatenate space-splitted text
AttributeError: 'NoneType' object has no attribute 'split'

なおlearn.pyは以下の通りです。

#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from glob import iglob
import re

import MeCab
import markovify


def load_from_file(files_pattern):
    """read and merge files which matches given file pattern, prepare for parsing and return it.
    """

    # read text
    text = ""
    for path in iglob(files_pattern):
        with open(path, 'r') as f:
            text += f.read().strip()

    # delete some symbols
    unwanted_chars = ['\r', '\u3000', '-', '|']
    for uc in unwanted_chars:
        text = text.replace(uc, '')

    # delete aozora bunko notations
    unwanted_patterns = [re.compile(r'《.*》'), re.compile(r'[#.*]')]
    for up in unwanted_patterns:
        text = re.sub(up, '', text)

    return text


def split_for_markovify(text):
    """split text to sentences by newline, and split sentence to words by space.
    """
    # separate words using mecab
    mecab = MeCab.Tagger()
    splitted_text = ""

    # these chars might break markovify
    # https://github.com/jsvine/markovify/issues/84
    breaking_chars = [
        '(',
        ')',
        '[',
        ']',
        '"',
        "'",
    ]

    # split whole text to sentences by newline, and split sentence to words by space.
    for line in text.split():
        mp = mecab.parseToNode(line)
        while mp:
            try:
                if mp.surface not in breaking_chars:
                    splitted_text += mp.surface    # skip if node is markovify breaking char
                if mp.surface != '。' and mp.surface != '、':
                    splitted_text += ' '    # split words by space
                if mp.surface == '。':
                    splitted_text += '\n'    # reresent sentence by newline
            except UnicodeDecodeError as e:
                # sometimes error occurs
                print(line)
            finally:
                mp = mp.next

    return splitted_text


def main():
    # load text
    rampo_text = load_from_file('hoge.txt')
    
    # split text to learnable form
    splitted_text = split_for_markovify(rampo_text)

    # learn model from text.
    text_model = markovify.NewlineText(splitted_text, state_size=5)

    # ... and generate from model.
    sentence = text_model.make_sentence()
    print(splitted_text)
    print(''.join(sentence.split()))    # need to concatenate space-splitted text

    # save learned data
    with open('learned_data.json', 'w') as f:
        f.write(text_model.to_json())

    # later, if you want to reuse learned data...
    """
    with open('learned_data.json') as f:
        text_model = markovify.NewlineText.from_json(f.read())
    """


if __name__ == '__main__':
    main()

また使用したテキストファイルは、メモ帳で適当な文章を書きhoge.txtとデスクトップに保存したやつです。
以上のようなエラーを解決するために、learn.pyのどれを書き直す/書き足せばよいでしょうか。なお上に貼ったリンクではpython3 learn.pyと実行するのが良いと最後に書いてあるのですがそれだと自分のは

C:\Users\Desktop>python3 learn.py
'python3' は、内部コマンドまたは外部コマンド、
操作可能なプログラムまたはバッチ ファイルとして認識されていません。

と表示されます。

4
  • jsvine/markovify とか markovify 0.7.1markovify が Python 3.6 系までしか検証していないようなので、Python の版数を 3.6 系に下げて入れなおしてみてはどうでしょう? 参考にされた記事も、インストールしておいて、と示した記事は Python 3.6.5 が入っているようですし。
    – kunif
    2019年3月9日 12:46
  • 3.6.5verにダウングレードしました。その後実行したらC:\Users\ikeda\Desktop>python learn.py Traceback (most recent call last): File "learn.py", line 100, in <module> main() File "learn.py", line 80, in main text_model = markovify.NewlineText(splitted_text, state_size=3) NameError: name 'splitted_text' is not defined というエラーが出ました 2019年3月9日 13:23
  • その呼び出し前に、rampo_txtsplitted_textprint してみて、意味のある中身が入っているか等を確かめてみてください。他には作るテキストを、参照記事で紹介している先のテキストから持ってくるとか、作成したテキストの encoding を変更できるエディタで encoding を変更してセーブして試してみてください。
    – kunif
    2019年3月9日 13:40
  • 解決しました!大変ありがとうございました!! 2019年3月9日 13:48

1 件の回答 1

1

jsvine/markovifyとかmarkovify 0.7.1markovify が Python 3.6 系までしか検証していないようなので、Python の版数を 3.6 系に下げて入れなおしてみてはどうでしょう?
参考にされた記事も「インストールしておいて」と示した記事は Python 3.6.5 が入っているようです。


この投稿は @kunif さんのコメントなどを元に編集し、コミュニティWikiとして投稿しました。

この質問に回答するには、ログインする必要があります。

求めていた回答ではありませんか? のタグが付いた他の質問を参照する。