-
Notifications
You must be signed in to change notification settings - Fork 0
/
analytica.py
211 lines (161 loc) · 6.19 KB
/
analytica.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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
# -*- coding: utf-8 -*-
"""
Created on Sat Aug 11 21:16:25 2018
@author: 13pra
"""
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.linear_model.logistic import LogisticRegression
from sklearn.model_selection import train_test_split, cross_val_score
import os
import nltk
nltk.download('punkt')
nltk.download('stopwords')
import math
import string
from nltk.corpus import stopwords
from collections import Counter
from nltk import ngrams
from nltk.stem.porter import *
import os
#, df2, df3, df4, df5, df6,df7, df8, df9, df10
files = [s for s in os.listdir() if s.endswith('.csv')]
filename = files
categories_df = pd.read_csv('C:\\Users\\13pra\\OneDrive\\Desktop\\Python\\KeywordCategory.csv')
categories_df=categories_df.drop_duplicates()
categories =pd.Series(categories_df.iloc[:,1])
categories.index =pd.Series(categories_df.iloc[:,0])
black_list = pd.read_csv('C:\\Users\\13pra\\OneDrive\\Desktop\\Python\\list_to_drop.csv',header = None)
m = list(black_list[0])
b = pd.DataFrame()
f = pd.DataFrame()
e = pd.DataFrame()
countlist = []
for file in filename:
d = pd.read_csv(file).dropna()
if not(d.empty):
d= d.sort_values(by = 'Location')
else:
continue
print(file)
d = d.reset_index(drop=True)
# initial cleaning
def get_tokens(text):
lowers = text.lower()
#remove the punctuation
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
no_punctuation = lowers.translate(remove_punctuation_map)
tokens = nltk.word_tokenize(no_punctuation)
return tokens
loctn = list(d['Location'])
#industry = list(d['Industry'])
l=set(loctn)
l = list(l)
# original count overall frequency
for locat in l:
file = d[d['Location']==locat]
comp_name = d[d['Location']==locat]['Company Name'].values[0]
ind = d[d['Location']==locat]['Industry'].values[0]
state = d[d['Location']==locat]['State'].values[0]
tokens = get_tokens(str(file['Job Title']))
count = Counter(tokens)
count.most_common(5)
# get rid of stop words/ numbers
filtered = [w for w in tokens if not w in stopwords.words('english')]
filtered = [w for w in filtered if not w.isdigit() == True]
filtered = [w for w in filtered if not len(w) <= 2]
# get rid of stemming
# stemmer = PorterStemmer()
# stemmed = stem_tokens(filtered, stemmer)
count = Counter(filtered)
# count.most_common(5)
# count_st = Counter(stemmed)
# count_st.most_common(5)
countlist.append(count)
twicegrams = ngrams(filtered, 2)
lst_combine = list()
for grams in twicegrams:
grams = grams[0] +" "+ grams[1]
lst_combine.append(grams)
count_twicegram = Counter(lst_combine)
countlist.append(count_twicegram)
a = count.most_common(len(count))
c = count_twicegram.most_common(len(count_twicegram))
a=pd.DataFrame(a)
a.columns = ['Keyword','count']
a['Company'] = comp_name
a['Location'] = locat
a['State'] = state
c = pd.DataFrame(c)
c.columns = ['Keyword','count']
c['Company'] = comp_name
c['Location'] = locat
c['State'] = state
b = b.append(a)
b['Industry'] = ind
b=b.append(c)
#scores = {word: tfidf(word, count, countlist) for word in count}
for i, count in enumerate(countlist):
scores = {word: tfidf(word, count, countlist) for word in count}
sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
sorted_words = dict(sorted_words)
e = pd.Series(sorted_words)
e =e.to_frame()
e.reset_index(level=0, inplace=True)
e.columns = ['Keyword','Tf-Idf']
f = f.append(e)
def stem_tokens(tokens, stemmer):
stemmed = []
for item in tokens:
stemmed.append(stemmer.stem(item))
return stemmed
def tf(word, count):
return count[word] / sum(count.values())
def n_containing(word, countlist):
return sum(1 for count in countlist if word in count)
def idf(word, countlist):
return math.log(len(countlist) / (1 + n_containing(word, countlist)))
def tfidf(word, count, countlist):
return tf(word, count) * idf(word, countlist)
#for i, count in enumerate(countlist):
# scores = {word: tfidf(word, count, countlist) for word in count}
# sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
# sorted_words = dict(sorted_words)
# e = pd.Series(sorted_words)
# e =e.to_frame()
# e.reset_index(level=0, inplace=True)
# e.columns = ['Keyword','Tf-Idf']
# f = f.append(e)
def idfchk(wrd):
if len(f[f['Keyword'] == wrd]['Tf-Idf'].values) !=0:
return f[f['Keyword'] == wrd]['Tf-Idf'].values[0]
#b = b.dropna()
#b = pd.merge(b,f, on='Keyword')
b['Category']=b.apply(lambda x: categories.get(x[2], x[2]).title(), axis=1)
b['Keyword'] = b['Keyword'].apply(lambda x: x if x not in m else np.NaN)
b['Tf-Idf'] = b['Keyword'].apply(idfchk)
b=b.dropna()
#b.to_csv('Fortune500_bigrms_tf.csv', sep=',', encoding='utf-8')
##################################
#### without stemming
#TF-IDF(t)=TF(t)×IDF(t)
def tf(word, count):
return count[word] / sum(count.values())
def n_containing(word, countlist):
return sum(1 for count in countlist if word in count)
def idf(word, countlist):
return math.log(len(countlist) / (1 + n_containing(word, countlist)))
def tfidf(word, count, countlist):
return tf(word, count) * idf(word, countlist)
def tfid_get(word):
global countlist
scores = idf(word,countlist)
return scores
#for i, count in enumerate(countlist):
# print("Top words")
# scores = {word: tfidf(word, count, countlist) for word in count}
# sorted_words = sorted(scores.items(), key=lambda x: x[1], reverse=True)
#
# for word, score in sorted_words[:10]:
# print("\tWord: {}, TF-IDF: {}".format(word, score))