usr bin python coding utf-8 import os from sklearn feature_extraction

 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
#!/usr/bin/python
# coding: utf-8
import os
from sklearn.feature_extraction.text import TfidfVectorizer
class Corpus():
def __init__(self, leftorright):
self.leftorright = leftorright
vectorizer = TfidfVectorizer(input='filename', analyzer='word')
filenames = []
for magazine in os.listdir('result_'+leftorright):
articles = os.listdir(os.path.join('result_'+leftorright, magazine))
filenames += [os.path.join('result_'+leftorright, magazine, x) for x in articles]
self.matrix = vectorizer.fit_transform(filenames)
self.vectorizer = vectorizer
self.feature_names = vectorizer.get_feature_names()
def get_tdidf_score(self, word):
index = self.vectorizer.vocabulary_.get(word)
return self.matrix[0,index]
left = Corpus('left')
print left.get_tdidf_score('rights')
#right = Corpus('right')
#print left.get_tdidf_score('tradition')
#print left.get_tdidf_score('traditions')