任意の文章を格納したテキストファイルからtfとidfを算出しようとしたところ、以下のエラーが出てしまいました。
解決に向けてお知恵をお貸しいただけますと幸いです。宜しくお願いします。
エラー
Traceback (most recent call last): File "renshu.py", line 105, in <module> idfs = math.log(num_lines / dfs) + 1 TypeError: unsupported operand type(s) for /: 'int' and 'dict'
コード
comp2.py
1import os 2import tweepy 3import redis 4import math 5from collections import Counter 6from collections import defaultdict 7import re 8from natto import MeCab 9import codecs 10import sys 11from sklearn.feature_extraction.text import TfidfVectorizer 12import glob 13import numpy as np 14import urllib.request 15from gensim import corpora 16from itertools import chain 17 18#日本語ツイートを読み込む + 文書数を表示 19count = 0 20with codecs.open("test.txt", "r", "utf-8") as f: 21 corpus = f.read().split("\n") 22 23num_lines = sum(1 for line in open("test.txt")) 24#print(num_lines) 25 26mecab = MeCab('-d /usr/local/lib/mecab/dic/mecab-ipadic-neologd') 27 28#ストップワードの読み込み 29stop_words = [] 30path = 'stop_words.txt' 31with open(path) as g: 32 stop_words = g.readlines() 33#url, 返信, RT, 絵文字の除去 34texts=[] 35for i in corpus: 36 texts.append(re.sub(r"http\S+", "", i)) 37 texts.append(re.sub(r"@(\w+) ", "", i)) 38 texts.append(re.sub(r"(^RT.*)", "", i, flags=re.MULTILINE | re.DOTALL)) 39 emoji_pattern = re.compile("[" 40 u"\U0001F600-\U0001F64F" 41 u"\U0001F300-\U0001F5FF" 42 u"\U0001F680-\U0001F6FF" 43 u"\U0001F1E0-\U0001F1FF" 44 "]+", flags=re.UNICODE) 45 texts.append(emoji_pattern.sub("", i)) 46texts.append(i) 47#print(mecab.parse(texts)) 48# texts = list(set(texts)) 49 50#名刺の抽出とスクリーニング 51docs = [] 52for txt in texts: 53 words = mecab.parse(txt, as_nodes=True) 54 doc = [] 55 #名詞の抽出と整形 56 rm_list = ["RT","https","co"] 57 for w in words: 58 if w.feature.split(",")[0] == "名詞": 59 if len(w.surface) >= 3: 60 if w.surface not in rm_list: 61 doc.append(w.surface) 62 #r.zincrby('words', 1.0, w.surface)#文書dにおける単語tの出現回数? 63 docs.append(doc) 64corpus = docs 65 66#重複単語の削除 67nouns = [] 68for line in corpus: 69 if line not in nouns: 70 nouns.append(line) 71 72tfs = [] # 記事毎のリスト。リスト要素は記事内の単語毎のtf値 73dfs = {} # 単語毎のdf値 74for idx,doc in enumerate(nouns): # idx=記事番号 75 tf = {} 76 for term in doc: 77 TERM_CNT = len(doc) # 記事内の単語数 78 79 # (記事内の)単語毎のtf値 80 if term not in tf: 81 tf[term] = 0 82 tf[term] += 1 / TERM_CNT # コード短縮のため、割り込むと同時に足す 83 84 # 単語毎のdf値 85 if term not in dfs: 86 dfs[term] = set() 87 dfs[term].add(idx) # 集合(set)で記事番号(idx)を保持 88 89 tfs.append(tf) 90 91# 記事番号の集合の大きさ=出現数 92for term,doc_set in dfs.items(): 93 dfs[term] = len(doc_set) 94 95idfs = math.log(num_lines / dfs) + 1 #問題の箇所 96 97print('nouns:',nouns) 98print('tfs:',tfs) 99print('idfs:',idfs)
ファイル
test.txt
1頭が使い物にならねえ 2課題も試験勉強も終わらないしミーティングもままならないからだめぽ 3唐揚げと天丼と二郎が食べたい 4実験終わらなかったし課題なんて知らない 5生物やPythonも好きだけど、今はPrologでラムダ記法や意味表現辺りをうにゃうにゃしたい人生だった
補足情報(FW/ツールのバージョンなど)
iOS 10.14.6, Python 3.7.4, Atom
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/10/23 03:47