/
vocabulary.py
107 lines (82 loc) · 3.75 KB
/
vocabulary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
import codecs
import os
import MeCab
import codecs
import unicodedata
from get_keywords import get_keywords
# ストップワード
# このURLのものを使用: https://qiita.com/kenmatsu4/items/9b6ac74f831443d29074
stop_words = [ u'てる', u'いる', u'なる', u'れる', u'する', u'ある', u'こと', u'これ', u'さん', u'して',
u'くれる', u'やる', u'くださる', u'そう', u'せる', u'した', u'思う',
u'それ', u'ここ', u'ちゃん', u'くん', u'', u'て',u'に',u'を',u'は',u'の', u'が', u'と', u'た', u'し', u'で',
u'ない', u'も', u'な', u'い', u'か', u'ので', u'よう', u'']
# どの放送でもよく出てくるワード
additional_stop_words = [
# u'イオリン', u'かわいい', u'すごい', u'かしこい', u'えらい', u'好き', u'すき', u'だいじょうぶ', u'大丈夫', u'いい',
u'w', u'ww', u'www', u'wwww', u'wwwww', u'wwwwww',
]
sw_set = set(stop_words + additional_stop_words)
m = MeCab.Tagger('-u ./dotlive.dic')
def get_mecab():
return m
def get_vocabulary_dic():
files = [os.path.join('livechat', f) for f in os.listdir('livechat')
if os.path.isfile(os.path.join('livechat', f))]
json_files = [f for f in files if os.path.splitext(f)[1] == '.json']
dic = {}
ignore_set = set()
for file in json_files:
vocabulary = {}
keywords = get_keywords(m, file, ['名詞','形容詞','感動詞'])
for keyword in keywords:
# ストップワードは除外
if keyword in sw_set:
continue
if keyword in vocabulary:
vocabulary[keyword] += 1
else:
if keyword in ignore_set:
continue
# 長さ1の場合は漢字のみ許可
# 造語の場合、漢字が一文字ずつばらされてしまって除外されてしまうとなかったことになってしまう
# それを防ぐために漢字の場合は1文字でも許可する
# (原理的には漢字以外でも同じ問題があるがすべてを許可してしまうとあまりにノイズが多すぎるので妥協する)
if len(keyword) == 1:
if not unicodedata.name(keyword, '').startswith('CJK UNIFIED'):
ignore_set.add(keyword)
continue
vocabulary[keyword] = 1
dic[file] = vocabulary
return dic
def flatten_vocabulary_dic(vocabulary_dic):
result = {}
for _, vocabulary in vocabulary_dic.items():
for keyword, count in vocabulary.items():
if keyword in result:
result[keyword] += count
else:
result[keyword] = count
return result
# キーワードが配信全体でどれだけ使用されているかを調べる
def calc_total_use_rate(vocabulary_dic):
# 配信回数
total_key_count = len(vocabulary_dic)
if total_key_count == 0:
return {}
dic = {}
for _, vocabulary in vocabulary_dic.items():
# ボキャブラリ内の全単語の全出現数
total_count = 0
for _, count in vocabulary.items():
total_count += count
for keyword, count in vocabulary.items():
# 全コメントの内、どれくらいを占めているか
rate = count / total_count
if keyword in dic:
dic[keyword] = dic[keyword] + rate
else:
dic[keyword] = rate
result = {}
for keyword, rate in dic.items():
result[keyword] = rate / total_key_count
return result