Django,CentOS7,MeCabでアプリケーションを作っています。
MeCabを動かそうとしたところ,以下のコードの
morpheme = node.surface
の部分で 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte
といったエラーが出ます。
こちらのウェブサイトなどなどを参考に,
エラーが出る部分の直前に
self.tagger = self.tagger.parse('')
と付け加えても同様のエラーが出ます。
どのようにすればエラーが解決するでしょうか?
python3
1class PrepareChain(object): 2 """ 3 チェーンを作成してDBに保存するクラス 4 """ 5 6 BEGIN = "__BEGIN_SENTENCE__" 7 END = "__END_SENTENCE__" 8 9 DB_PATH = "chain.db" 10 DB_SCHEMA_PATH = "schema.sql" 11 12 def __init__(self, text): 13 """ 14 初期化メソッド 15 @param text チェーンを生成するための文章 16 """ 17 if isinstance(text, bytes): 18 text = text.decode('utf-8') 19 self.text = text 20 21 # 形態素解析用タガー 22 self.tagger = MeCab.Tagger('-Ochasen') 23 24 def make_triplet_freqs(self): 25 """ 26 形態素解析から3つ組の出現回数まで 27 @return 3つ組とその出現回数の辞書 key: 3つ組(タプル) val: 出現回数 28 """ 29 # 長い文章をセンテンス毎に分割 30 sentences = self._divide(self.text) 31 32 # 3つ組の出現回数 33 triplet_freqs = defaultdict(int) 34 35 # センテンス毎に3つ組にする 36 for sentence in sentences: 37 # 形態素解析 38 morphemes = self._morphological_analysis(sentence) 39 # 3つ組をつくる 40 triplets = self._make_triplet(morphemes) 41 # 出現回数を加算 42 for (triplet, n) in list(triplets.items()): 43 triplet_freqs[triplet] += n 44 45 return triplet_freqs 46 47 def _divide(self, text): 48 """ 49 「。」や改行などで区切られた長い文章を一文ずつに分ける 50 @param text 分割前の文章 51 @return 一文ずつの配列 52 """ 53 # 改行文字以外の分割文字(正規表現表記) 54 delimiter = "。|.|." 55 56 # 全ての分割文字を改行文字に置換(splitしたときに「。」などの情報を無くさないため) 57 text = re.sub(r"({0})".format(delimiter), r"\1\n", text) 58 59 # 改行文字で分割 60 sentences = text.splitlines() 61 62 # 前後の空白文字を削除 63 sentences = [sentence.strip() for sentence in sentences] 64 65 return sentences 66 67 def _morphological_analysis(self, sentence): 68 """ 69 一文を形態素解析する 70 @param sentence 一文 71 @return 形態素で分割された配列 72 """ 73 morphemes = [] 74 node = self.tagger.parseToNode(sentence) 75 while node: 76 if node.posid != 0: 77 ****morpheme = node.surface**** 78 morphemes.append(morpheme) 79 node = node.next 80 return morphemes 81 82
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。