前提・実現したいこと
テキストファイルをmecab-ipadic-neologdを使って形態素解析し、動詞と形容詞だけを抜き出し、テキストファイルに出力。
発生している問題・エラーメッセージ
このコードは青空文庫のものに対しては対応しているが、普通のテキストファイルには適していない。
該当のソースコード
Python
ソースコード
import MeCab
import re
bindata = open('ningen_shikkaku.txt', 'rb').read()
textdata = bindata.decode('shift_jis')
textdata = re.split(r'-{5,}', textdata)[2]
textdata = re.split(r'底本:', textdata)[0]
textdata = textdata.strip()
mecab = MeCab.Tagger('-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd')
mecab.parse('')
results = []
lines = textdata.split("\r\n")
for line in lines:
r = []
s = line
s = s.replace("|", "")
s = re.sub(r'《.+?》', "", s)
s = re.sub(r'[.+?]', '', s)
node = mecab.parseToNode(s) while node: if node.feature.split(",")[6] == '*': word = node.surface else: word = node.feature.split(",")[6] part = node.feature.split(",")[0] if part in ["形容詞", "動詞"]: r.append(word) node = node.next rl = (" ".join(r)).strip() results.append(rl)
w_file = "ningen_result.txt"
with open(w_file, 'w', encoding='utf-8') as wf:
wf.write("\n".join(results))
試したこと
textdataという部分をなくし、テキストファイルがそのままlinesに入るようにしてみたがだめだった。
補足情報(FW/ツールのバージョンなど)
ここにより詳細な情報を記載してください。
あなたの回答
tips
プレビュー