/
process_data.py
143 lines (96 loc) · 2.52 KB
/
process_data.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
import os
import lxml.html
from nltk import PorterStemmer
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import stopwords
from string import maketrans
import os, json, MySQLdb
from lib.mysql import connection
from lib.datacleaner import DataClean
#Preprocess the RCV1 Dataset
#Globals
lmtzr = WordNetLemmatizer()
porter_stem = PorterStemmer()
wordnet_tag ={'NN':'n','JJ':'a','VB':'v','RB':'r'}
topics = {
'entertain' : ['ENT12','GENT','GFAS'],
#'politics' : ['1POL','G12','GPOL'],
#'econonics' : ['2ECO','E11','E12','ECAT'],
#'sports' : ['3SPO','GSPO'],
'education' : ['G113','GEDU','C23','GSCI'],
'religion' : ['GREL'],
#'health' : ['G111','GHEA'],
}
print "Init"
def addslashes(s):
l = ["\\", '"', "'", "\0", ]
for i in l:
if i in s:
s = s.replace(i, '\\'+i)
return s
def dbwrite(p,x1,x2):
try :
connection = MySQLdb.connect('localhost', 'root', 'kgggdkp2692', 'mining')
except Exception as e :
connection =None
print "Unable to connect :" + str(e)
x = connection.cursor()
try:
q= "INSERT INTO `data_new` (`path`,`topic`,`data`) VALUES ('"+str(p)+"','"+json.dumps(x1).replace('\'', '\\\'')+"','"+json.dumps(x2).replace('\'', '\\\'')+"')"
x.execute(q)
connection.commit()
except Exception as e :
print e
connection.rollback()
connection.close()
def GetDirList(cur_dir, list):
for root, dirs, files in os.walk(cur_dir):
for name in files:
if name.endswith('.xml'):
list.append(os.path.join(root, name))
for name in dirs:
GetDirList(os.path.join(root, name),list)
return list
list =[]
list.sort()
list = GetDirList(os.getcwd(),list)
count = 0
#list.sort(reverse=True)
print "Counted..Processing "
for path in list :
count =count +1
try:
try :
f = open(path , 'r')
text = str(f.read())
except Exception as E :
print "FILE ERROR" , E
finally :
f.close()
os.remove(path)
list.remove(path)
doc = lxml.html.document_fromstring(text)
txt2 = doc.xpath("//codes[@class='bip:topics:1.0']/code/@code")
flag = 0
id1 = doc.xpath("//newsitem/@itemid")
top = []
for i in txt2 :
for k in topics:
if i in topics[k]:
flag =1
if k in top :
pass
else :
top.append(k)
if flag == 1 :
txt1 = doc.xpath("//p/text()")
lis = []
for i in txt1 :
l=DataClean(i).GetData()
lis.append(l)
dbwrite(id1[0],top,lis)
print top ,count ,len(list)
if ( count % 1000 == 0 ):
print count , len(list)
except Exception as e :
print e , path ,str(count)