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

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

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

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

Q&A

解決済

1回答

1065閲覧

pyファイルを起動してテキストマイニングを表示したいがエラー

yasu777

総合スコア1

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

0グッド

0クリップ

投稿2021/04/14 03:18

前提・実現したいこと

pyファイルを起動してテキストマイニングを表示したい

発生している問題・エラーメッセージ

------------------- ERROR DETAILS ------------------------ arguments: Owakati error message: [ifs] no such file or directory: c:\mecab\mecabrc ---------------------------------------------------------- Traceback (most recent call last): File "C:\Python\11f_wordcloud.py", line 118, in <module> tokens = Wakati(text).tokenize() File "C:\Python\11f_wordcloud.py", line 58, in tokenize words = self.get_words() File "C:\Python\11f_wordcloud.py", line 89, in get_words dfw = self.get_dfw() File "C:\Python\11f_wordcloud.py", line 64, in get_dfw t = MeCab.Tagger("Owakati") File "C:\Users***\AppData\Local\Programs\Python\Python37\lib\site-packages\MeCab\__init__.py", line 124, in __init__ super(Tagger, self).__init__(args) RuntimeError

該当のソースコード

#!/usr/bin/env python
import os,matplotlib,re,MeCab,itertools,pydotplus,requests,io,string
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt

coding: utf-8

#!/usr/bin/env python
from wordcloud import WordCloud
from PIL import Image
import numpy as np
from collections import Counter
import MeCab as amee
from igraph import *
from bs4 import BeautifulSoup
import pandas as pd
from os import path
from collections import Counter

#「.txtファイル」からテキストを抽出するための関数
def get_text(path):
f = open(path, encoding="utf-8")
text = f.read()
f.close()
return text

形態素解析開始

class Wakati:
# コンストラクタ
def init(self, text):
self.text = text
self.tokens = None
self.targets = ["名詞", "動詞", "形容詞"]

# 除外したいNGワードリスト〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓
self.stopwords = [u'てる']

# 分かち書きを行うメソッド
def tokenize(self):
words = self.get_words()
self.tokens = self.get_stopped_words(words)
return self.tokens

# 形態素解析の結果をDataFrameで返す関数
def get_dfw(self):
t = MeCab.Tagger("Owakati")
t.parse("")
node = t.parseToNode(self.text)

surfaces = []
stems = []
poss = []

while node: surface = node.surface feature = node.feature.split(",") stem = feature[6] pos = feature[0] surfaces.append(surface) stems.append(stem) poss.append(pos) node = node.next dfw = pd.DataFrame() dfw["SURFACE"] = surfaces[1:-1] dfw["STEM"] = stems[1:-1] dfw["POS"] = poss[1:-1] return dfw


# 形態素解析結果から目的となる品詞に一致した単語リストを取得する関数
def get_words(self):
dfw = self.get_dfw()
words = []
for row in dfw.iterrows():
for target_pos in self.targets:
if row[1]["POS"] == target_pos:
if row[1]["STEM"] != "*":
words.append(row[1]["STEM"])
return words

# 単語リストからストップワードを除去した単語リストを返す関数
def get_stopped_words(self, words):
stopped_words = [word for word in words if word not in self.stopwords]
return stopped_words

トークンリストを半角スペースで結合したテキストに変換する関数

def tokens2linetext(tokens):
linetext = ""
for token in tokens:
linetext += token
linetext += " "
return linetext[:-1]

テキストデータの取り込み〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓

path = u"C:/python/00__text/指定のテキスト.txt"
text = get_text(path)

テキストの形態素解析

tokens = Wakati(text).tokenize()

形態素解析結果を半角スペースで結合されたテキストに変換

linetext = tokens2linetext(tokens)

フォントパスの準備

fontpath = "C:/python/08__font/AozoraMinchoHeavy.ttf"

WordCloudの外形画像の準備〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓

mask_path = "C:/python/01__image/指定の枠.png"
datum_mask = np.array(Image.open(mask_path))

除外したいNGワードリスト〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓〓

stopwords = [u'てる']

パラメータ

wc = WordCloud(
background_color="white",
colormap="Reds",
#mask=datum_mask,
font_path=fontpath,
collocations=False,
stopwords=stopwords,
max_font_size=100,
#min_font_size=30,
#max_words=3,
ranks_only=False,
random_state=None,
prefer_horizontal=0.9,# 「縦書き」の比率
#mode="RGBA",
#scale=1,
height=600,
width=900
)
wc.generate(text) #「text」短文、「linetext」単語

出力ファイル名設定と単語頻度図の出力

filename = os.path.basename(path)
filename = os.path.splitext(filename)[0]
outname = "wordcloud_" + filename + "(フレーズ)" + ".png"
wc.to_file(outname)

#出力!
print("出力準備完了!")
plt.figure(figsize=(15,9))
plt.imshow(wc)
plt.axis("off")
plt.show()

形態素解析の結果をShellに掲載

m = MeCab.Tagger("-Ochasen")
mecablist =[]
wlist =m.parse(text).splitlines()
for u in wlist:
xlist = []
for v in u.split():
xlist.append(v)
mecablist.append(xlist)

wordbodylist =[]
for u in mecablist:
wordbodylist.append(u[0])
cnt = Counter(wordbodylist)
print(sorted(cnt.items(), key=lambda x: x[1], reverse=True)[:400])

試したこと

mecab再インストール
辞書ipdic再インストール

補足情報(FW/ツールのバージョンなど)

mecabrcはないが、なくても成功する人がいる
辞書ipdicの利用でも成功する人がいる
pipは最新に更新済み

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

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

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

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

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

guest

回答1

0

自己解決

mecabrcファイルを作成した事で次のステップに進めました。

投稿2021/04/14 03:56

yasu777

総合スコア1

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

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

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

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

ただいまの回答率
85.48%

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

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

質問する

関連した質問