-
Notifications
You must be signed in to change notification settings - Fork 0
/
Read_And_Clean.py
179 lines (129 loc) · 4.97 KB
/
Read_And_Clean.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
from rdflib import Graph, URIRef, ConjunctiveGraph
from Utils.Filename import Filename
from Utils.Constants import Constants
from pathlib import Path
import time
import os
import re
import regex
import nltk
from spellchecker import SpellChecker
from nltk.stem.wordnet import WordNetLemmatizer
from nltk.corpus import wordnet as wn
def removeNumbers(list):
pattern = '[0-9]'
list = [re.sub(pattern, '', i) for i in list]
return list
def removeMistakes(text):
spell = SpellChecker()
# find those words that may be misspelled
misspelled = spell.unknown(text)
nomistakes = set(text) - set(misspelled)
return nomistakes
def removeNonEnglish(text):
cleaned = " ".join(w for w in text if w.lower() in words or not w.isalpha())
cleaned = cleaned.split()
return cleaned
def tokenize(text):
result = nltk.word_tokenize(text)
return result
def get_lemma2(word):
return WordNetLemmatizer().lemmatize(word)
def get_lemma(word):
lemma = wn.morphy(word)
if lemma is None:
return word
else:
return lemma
def toLower(text):
return text.lower()
def removePunctuation(list):
remove = regex.compile(r'[\p{C}|\p{M}|\p{P}|\p{S}|\p{Z}]+', regex.UNICODE)
text = remove.sub(u" ", list).strip()
return text
def processTextForLDA(text):
# Lower case
text = toLower(text)
# Remove punctuation
text = removePunctuation(text)
# Tokenize
tokens = tokenize(text)
# Remove numbers
tokens = removeNumbers(tokens)
# Remove stop words
tokens = [token for token in tokens if token not in en_stop]
# Lemmatization
tokens = [get_lemma(token) for token in tokens]
# Remove small tokens
tokens = [token for token in tokens if len(token) > 2]
# Remove mistakes
tokens = removeMistakes(tokens)
# Remove non-English words
tokens = removeNonEnglish(tokens)
tokens = [token for token in tokens if token]
cleanText = " ".join(tokens)
return cleanText
def writeFiles(filename, rawText, cleanText):
with open(filename.raw_concept_filename, 'a', encoding="utf8") as f:
f.write('\n'.join(rawText))
f.write('\n')
# Write clean file
with open(filename.clean_concept_filename, 'a', encoding="utf8") as f:
f.write('\n'.join(cleanText))
f.write('\n')
def processFile(filenameSubset):
try:
global total_concepts
start_time = time.time()
os.makedirs(os.path.dirname(filenameSubset.raw_concept_filename), exist_ok=True)
os.makedirs(os.path.dirname(filenameSubset.clean_concept_filename), exist_ok=True)
g = ConjunctiveGraph()
data = open(filenameSubset.nq_filename, "rb")
g.parse(data, format="nquads")
### Get All Contexts
i = 0
for ctx in g.contexts():
i = i + 1
concept_url = ''
concept = ''
for subject, predicate, obj in ctx:
concept_url = subject
concept = str(concept_url).replace(Constants.ConceptPrefix, '')
break
node_identifier = ctx.identifier
cleanTexts = []
rawTexts = []
if (str(concept_url).startswith(Constants.ConceptPrefix)):
# create file for concept
filename = Filename(str(concept))
path = Path(filename.raw_concept_filename)
path.parent.mkdir(parents=True, exist_ok=True)
path = Path(filename.clean_concept_filename)
path.parent.mkdir(parents=True, exist_ok=True)
wasDerivedFrom_objects = g.objects(subject=node_identifier, predicate=URIRef(Constants.wasDerivedFrom))
for wasDerivedFrom in wasDerivedFrom_objects:
provValues = g.objects(subject=wasDerivedFrom, predicate=URIRef(Constants.provValue))
for provValue in provValues:
rawTexts.append(provValue)
clean_text = processTextForLDA(provValue)
cleanTexts.append(clean_text)
writeFiles(filename, rawTexts, cleanTexts)
total_concepts = total_concepts + i
print('Finished Processing: ' + filenameSubset.nq_filename + ' ,Concepts:' + str(i) + ' ,Total Concepts:' + str(total_concepts) + ", --- %s seconds ---" % (time.time() - start_time))
except Exception as e:
print('Error processing File: ' + filenameSubset.nq_filename + ' ,' + str(e))
total_concepts = 0
en_stop = None
words = None
if __name__ == '__main__':
start_time = time.time()
nltk.download('punkt')
nltk.download('words')
filename = Filename('subset-1')
en_stop = set(nltk.corpus.stopwords.words('english'))
words = set(nltk.corpus.words.words())
try:
processFile(filename)
except:
print('Error processing File: ' + filename.nq_filename)
print('Concept files cleaned and saved, --- %s minutes ---' % ((time.time() - start_time) / 60), flush=True)