-
Notifications
You must be signed in to change notification settings - Fork 47
/
tfidf.py
91 lines (72 loc) · 2.4 KB
/
tfidf.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
#!/usr/bin/python
# -*- coding: utf-8 -*-
from segmenter import segment
import sys, getopt
class IDFLoader(object):
def __init__(self, idf_path):
self.idf_path = idf_path
self.idf_freq = {} # idf
self.mean_idf = 0.0 # 均值
self.load_idf()
def load_idf(self): # 从文件中载入idf
cnt = 0
with open(self.idf_path, 'r', encoding='utf-8') as f:
for line in f:
try:
word, freq = line.strip().split(' ')
cnt += 1
except Exception as e:
pass
self.idf_freq[word] = float(freq)
print('Vocabularies loaded: %d' % cnt)
self.mean_idf = sum(self.idf_freq.values()) / cnt
class TFIDF(object):
def __init__(self, idf_path):
self.idf_loader = IDFLoader(idf_path)
self.idf_freq = self.idf_loader.idf_freq
self.mean_idf = self.idf_loader.mean_idf
def extract_keywords(self, sentence, topK=20): # 提取关键词
# 过滤
seg_list = segment(sentence)
freq = {}
for w in seg_list:
freq[w] = freq.get(w, 0.0) + 1.0
total = sum(freq.values())
for k in freq: # 计算 TF-IDF
freq[k] *= self.idf_freq.get(k, self.mean_idf) / total
tags = sorted(freq, key=freq.__getitem__, reverse=True) # 排序
if topK:
return tags[:topK]
else:
return tags
def main(argv):
idffile = ''
document = ''
topK = None
usage = 'usage: python tfidf.py -i <idffile> -d <document> -t <topK>'
if len(argv) < 4:
print(usage)
sys.exit()
try:
opts, args = getopt.getopt(argv,"hi:d:t:",
["idffile=","document=", "topK="])
except getopt.GetoptError:
print(usage)
sys.exit(2)
for opt, arg in opts: # parsing arguments
if opt == '-h':
print(usage)
sys.exit()
elif opt in ("-i", "--idffile"):
idffile = arg
elif opt in ("-d", "--document"):
document = arg
elif opt in ("-t", "--topK"):
topK = int(arg)
tdidf = TFIDF(idffile)
sentence = open(document, 'r', encoding='utf-8', errors='ignore').read()
tags = tdidf.extract_keywords(sentence, topK)
for tag in tags:
print(tag)
if __name__ == "__main__":
main(sys.argv[1:])