-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocess.py
406 lines (304 loc) · 14 KB
/
preprocess.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
# -*- coding: utf-8 -*-
"""
This file should contain functions for the following operations:
- load data from raw txt format (in German)
- stemming
- (maybe) remove stop-words (e.g. der, die, das, in, am ...)
- create dictionary containing all desired words
"""
import os
import fnmatch
import re
from nltk.stem.snowball import GermanStemmer
import nltk
import sys
from nltk.corpus import stopwords
import chardet
def setup():
# setup needed libraries, directories etc. TODO construct need directories automatically
nltk.download('punkt')
class TokenizerBase():
def split_to_words(self, s, delimiter='[.,?!:; {}()"\[" "\]"" "\n"]'):
l = re.split(delimiter, s)
l = [v for v in l if v != ''] #remove all empty strings
return l
def replace_umlauts(self, text):
res = text
return res
def replace_special_chars(self, text):
res = text
res = res.replace(u'ß', 'ss')
res = res.replace(u'—', '-')
return res
class SimpleGermanTokenizer(TokenizerBase):
def tokenize(self, s):
words = self.split_to_words(s)
stemmed_words = self.stem_words(words)
return stemmed_words
def stem_words(self, words):
stemmer = GermanStemmer()
stemmed_words = []
for word in words:
stemmed_words.append(stemmer.stem(word))
return stemmed_words
class NonStemmingTokenizer(TokenizerBase):
# https://github.com/devmount/GermanWordEmbeddings/blob/master/preprocessing.py
def tokenize(self, s):
# punctuation and stopwords
punctuation_tokens = ['.', '..', '...', ',', ';', ':', '"', u'„', '„', u'“', '“', '\'',
'[', ']', '{', '}', '(', ')', '<', '>', '?', '!', '-', u'–', '+',
'*', '--', '\\', '\'\'', '``', '‚', '‘', '\n', '\\n', '']
punctuation = ['?', '.', '!', '/', ';', ':', '(', ')', '&', '\n']
# Define at which chars you want to split words
# split_chars = ['-', '/', '\\\\', '+', '|']
split_chars = ['/', '\\\\', '+', '|']
# stop_words = [self.replace_umlauts(token) for token in stopwords.words('german')]
# replace umlauts
s = self.replace_umlauts(s)
# replace newline chars
def remove_newlines(document):
document = re.sub('\\n', ' ', document)
document = re.sub('\\\\n', ' ', document)
document = re.sub('\n', ' ', document)
return document
s = remove_newlines(s)
s = self.replace_special_chars(s)
# get word tokens
words = nltk.word_tokenize(s)
# filter punctuation tokens
words = [x for x in words if x not in punctuation_tokens]
# remove stopwords
# words = [x for x in words if x not in stop_words]
# split words at defined characters
delimiters = '[' + "".join(split_chars) + ']'
flat_words = []
for x in words:
flat_words.extend(re.split(delimiters, x))
words = flat_words
# functions to remove all punctuations at the beginning and end of a word
# (in case something in the nltk.word_tokenize() was left over)
def remove_start_punct(word):
while word and (word[0] in punctuation_tokens):
word = word[1:]
return word
def remove_end_puntc(word):
while word and (word[-1] in punctuation_tokens):
word = word[:-1]
return word
# remove all punctuations at the beginning and ending of a word
words = [remove_start_punct(x) for x in words]
words = [remove_end_puntc(x) for x in words]
# remove all undesired punctuations at any location
words = [re.sub('[' + "".join(punctuation) + ']', '', x) for x in words]
# process words
words = [x.lower() for x in words]
# remove everything except
words = [re.sub(r'[^a-z0-9%ÜÖÄÉÈÀéèàöäü=><†@≥≤\s\-\/]', '', x) for x in words]
# remove stopwords TODO activate maybe
# words = [x for x in words if x not in stop_words]
return words
class SentenceExtractor():
# not used so far
# idea from https://github.com/devmount/GermanWordEmbeddings/blob/master/preprocessing.py
def extract_sentences(self, s):
# sentence detector
sentence_detector = nltk.data.load('tokenizers/punkt/german.pickle')
sentences = sentence_detector.tokenize(s)
return sentences
def make_directory(base_directory, new_subdirectory):
new_subdir_path = os.path.join(base_directory, new_subdirectory)
if not os.path.exists(new_subdir_path):
os.makedirs(new_subdir_path)
def get_tokens_from_file(file, tokenizer):
"""
reads file and returns a list of all ovserved tokens (stemmed)
"""
file.seek(0) # reset file iterator
data = file.read()
tokens = tokenizer.tokenize(data)
return tokens
def tokens_from_dir(directory, tokenizer, train_file=None, valid_tokens=None):
"""
creates tokens using all *.txt files of any subdirectory of 'directory'
:param train_file: if train_file is specified, store all tokens in
train_file
:param valid_tokens: if valid_tokens is specified, only keep the tokens that
occur in valid_tokens
:return: tokenized vocabulary, or: set of all tokens found in any file
(note: not the tokenized content, only a set of all tokens)
"""
""""
-
- if valid_tokens is specified, only keep the tokens that occur in
valid_tokens
"""
print("Read and tokenize data from directory '", directory, "'")
tokenSet = set()
total_tokens = 0
n_files = 0
n_bad_encoding = 0
# iterate over all .txt files
for dirpath, dirs, files in os.walk(directory, followlinks=True):
for filename in fnmatch.filter(files, '*.txt'):
n_files += 1
sys.stdout.write( "Reading File "+ str(n_files) + '\r')
#try to find the encoding
encodingInfo = chardet.detect(open(os.path.join(dirpath, filename),
"rb").read())
# skip the file, if the encoding is unknown
encoding = encodingInfo['encoding'];
if (not encoding or encodingInfo['confidence'] < 0.8):
n_bad_encoding +=1
continue
with open(os.path.join(dirpath, filename), 'r', encoding=encoding) \
as file:
# create tokens from each file
tokens = get_tokens_from_file(file, tokenizer)
if(valid_tokens is not None):
# remove all tokens, which are not in valid_tokens
tokens = [t for t in tokens if t in valid_tokens]
if (train_file is not None):
# append token_string to train_file
token_string = " ".join(tokens) + " \n"
# replace multiple whitespaces with a single one
token_string = re.sub('\s+', ' ', token_string)
# save in utf-8 format
# TODO remove illegal non-utf-8 symbols
# (read and write should decode and encode in utf-8 by standard in python3,
# the once appeared error could not be reconstructed)
train_file.write(token_string)
# build set of all tokens and count total number of found tokens
tokenSet |= set(tokens)
total_tokens += len(tokens)
file.close()
n_good_files = n_files - n_bad_encoding
print("Found %d different tokens in %d articles, total training size: "
"%d tokens." % (len(tokenSet), n_good_files , total_tokens))
print("%d files could not be decoded." % n_bad_encoding)
return tokenSet;
def get_tokenizer(config):
tk = config.config['tokenizer']
if tk == 'sgt':
tokenizer = SimpleGermanTokenizer()
elif tk == 'nst':
tokenizer = NonStemmingTokenizer()
else:
# Default
print("Warining: Couldn't find specified tokenizer. Continuing with default tokenizer. ")
tokenizer = NonStemmingTokenizer()
return tokenizer
def create_train_data(train_data_src, raw_data_dir, config):
print("Creating new training data. ")
### Create needed token-datastructures
tokenizer = get_tokenizer(config)
print("Using this Tokenizer: ", str(tokenizer.__class__).split('.')[1].split("'")[0])
# open training data file
train_file = open(train_data_src, 'w+')
# Create tokens from raw_data_dir and store them in train_file
tokens_from_dir(raw_data_dir, tokenizer, train_file)
# close training date file
train_file.close()
def create_intersection_train_data(train_data_src, train_data_dir, config):
"""
# remove irregular tokens from pdf-data webcrawler-data and wiki_dumps:
1) generate vocab set for pdf-data, webcrawler-data, wiki_dumps
independently
2) keep only vocab, which occurs in all sets (intersection-set)
3) when creating the train data, remove words which are not in
intersection set by a TBD-strategy (e.g. remove only word, remove line,
remove sentence ...)
# Verification of relevance:
# - check words which are not in intersection manually
# - ...
"""
raw_data_dir = os.path.join(train_data_dir, 'raw_data/')
# assumes the following sub-folders
pdf_folder = os.path.join(raw_data_dir, 'medical_books_plaintxt/')
crawler_folder = os.path.join(raw_data_dir, 'medtextcollector_output/')
wiki_folder = os.path.join(raw_data_dir, 'wiki_dumps_txts/')
codes_folder = os.path.join(raw_data_dir, 'ICD_CHOP/')
print("Creating new intersection training data. ")
### Create needed token-datastructures
tokenizer = get_tokenizer(config)
print("Using this Tokenizer: ",
str(tokenizer.__class__).split('.')[1].split("'")[0])
# Create tokens from raw_data_dir and store them in train_file
pdf_token_set = tokens_from_dir(pdf_folder, tokenizer)
crawler_token_set = tokens_from_dir(crawler_folder, tokenizer)
wiki_token_set = tokens_from_dir(wiki_folder, tokenizer)
# compute intersection
#TODO maybe test with intersection of PDF and crawler data only
intersection_token_set = pdf_token_set & (crawler_token_set | wiki_token_set)
### DEBUG & INSPECTION ###
# compute remaining parts (for debug / inspection purpose)
remain_pdf_token_set = pdf_token_set - intersection_token_set
remain_crawler_token_set = crawler_token_set - intersection_token_set
remain_wiki_token_set = wiki_token_set - intersection_token_set
# save sets for inspection
file_names = ['pdf_set', 'crawler_set', 'wiki_set', 'inter_set',
'pdf_excl', 'crawler_excl', 'wiki_excl']
for i, data_set in enumerate([pdf_token_set, crawler_token_set,
wiki_token_set, intersection_token_set,
remain_pdf_token_set,
remain_crawler_token_set,
remain_wiki_token_set]):
out_src = os.path.join(train_data_dir, 'processed_data/' +
file_names[i] + '.txt')
with open(out_src, 'w') as file:
file.writelines([item + '\n' for item in data_set])
### END DEBUG & INSPECTION ###
# open training data file
train_file = open(train_data_src, 'w+')
# Create tokens from multiple dirs and append them to train_file
# only tokens included in valid_tokens are kept
directories = [pdf_folder, crawler_folder, wiki_folder]
for dir in directories:
tokens_from_dir(dir, tokenizer, train_file,
valid_tokens=intersection_token_set)
# also add CHOP and ICD tokens to train_file but keep all (not only the ones
# that are in intersection_token_set)
tokens_from_dir(codes_folder, tokenizer, train_file, valid_tokens=None)
# close training date file
train_file.close()
# ### DEBUG & INSPECTION ###
# return pdf_token_set, crawler_token_set, wiki_token_set, \
# intersection_token_set, remain_pdf_token_set, \
# remain_crawler_token_set, remain_wiki_token_set
# ### END DEBUG & INSPECTION ###
def load_intersection_data():
"""
Load token sets from different text-sources (PDFs, web-crawler, wiki-dumps)
to analyse them.
Function used only for Debug / Analysis.
"""
# TODO replace hardcoding for further development
dir = 'data/train_data/processed_data/'
pdf_src = os.path.join(dir, 'pdf_set.txt')
crawler_src = os.path.join(dir, 'crawler_set.txt')
wiki_src = os.path.join(dir, 'wiki_set.txt')
# load sets
files = [pdf_src, crawler_src, wiki_src]
sets = []
for file in files:
with open(file) as f:
temp = [line[:-1] for line in f]
sets.append(set(temp))
[pdf_token_set, crawler_token_set, wiki_token_set] = sets
intersection_token_set = pdf_token_set & (wiki_token_set | crawler_token_set)
# compute remaining parts (for debug / inspection purpose)
remain_pdf_token_set = pdf_token_set - intersection_token_set
remain_crawler_token_set = crawler_token_set - intersection_token_set
remain_wiki_token_set = wiki_token_set - intersection_token_set
# save sets for inspection
file_names = ['pdf_set', 'crawler_set', 'wiki_set', 'inter_set',
'pdf_excl', 'crawler_excl', 'wiki_excl']
for i, data_set in enumerate([pdf_token_set, crawler_token_set,
wiki_token_set, intersection_token_set,
remain_pdf_token_set,
remain_crawler_token_set,
remain_wiki_token_set]):
out_src = os.path.join(dir, 'new_inters',
file_names[i] + '.txt')
with open(out_src, 'w') as file:
file.writelines([item + '\n' for item in data_set])
return sets[0], sets[1], sets[2], sets[3], intersection_token_set