-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtfidf_vectorizer.py
More file actions
31 lines (24 loc) · 996 Bytes
/
Copy pathtfidf_vectorizer.py
File metadata and controls
31 lines (24 loc) · 996 Bytes
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
from sklearn.feature_extraction.text import TfidfVectorizer
import os
def load_documents(directory):
documents = []
for filename in os.listdir(directory):
if filename.endswith(".txt"):
with open(os.path.join(directory, filename), 'r', encoding='utf-8') as file:
documents.append(file.read())
return documents
def create_tfidf_matrix(documents):
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(documents)
return tfidf_matrix, vectorizer
def get_tfidf_matrix(directory):
documents = []
file_names = []
for filename in os.listdir(directory):
if filename.endswith(".txt"):
with open(os.path.join(directory, filename), 'r', encoding='utf-8') as file:
documents.append(file.read())
file_names.append(filename)
vectorizer = TfidfVectorizer()
tfidf_matrix = vectorizer.fit_transform(documents)
return tfidf_matrix, vectorizer, file_names