+ mwe_tokenize = MWETokenizer().tokenize
+
+ def remove_punct(sentence):
+ new_sentence = []
+ for token in sentence:
+ new_token = ''
+ for c in token:
+ if c not in string.punctuation:
+ new_token += c
+ if len(new_token) > 0:
+ new_sentence.append(new_token)
+ return new_sentence
+
+
+ stopWords = set(stopwords.words('english'))
+
+ # we follow the approach described in datta, phelan, adar 2017
+ def my_tokenizer(text):
+ # remove stopwords, punctuation, urls, lower case
+ # lowercase
+ text = text.lower()
+
+ # remove urls
+ text = urlregex.sub("", text)
+
+ # sentence tokenize
+ sentences = sent_tokenize(text)
+
+ # wordpunct_tokenize
+ sentences = map(wordpunct_tokenize, sentences)
+
+ # remove punctuation
+
+ sentences = map(remove_punct, sentences)
+
+ # remove sentences with less than 2 words
+ sentences = filter(lambda sentence: len(sentence) > 2, sentences)
+
+ # datta et al. select relatively common phrases from the reddit corpus, but they don't really explain how. We'll try that in a second phase.
+ # they say that the extract 1-4 grams from 10% of the sentences and then find phrases that appear often relative to the original terms
+ # here we take a 10 percent sample of sentences
+ if mwe_pass == 'first':
+ sentences = list(sentences)
+ for sentence in sentences:
+ if random() <= 0.1:
+ grams = list(chain(*map(lambda i : ngrams(sentence,i),range(4))))
+ with open(f'/gscratch/comdata/users/nathante/reddit_comment_ngrams_10p_sample/{ngram_output}','a') as gram_file:
+ for ng in grams:
+ gram_file.write(' '.join(ng) + '\n')
+ for token in sentence:
+ if token not in stopWords:
+ yield token
+
+ else:
+ # remove stopWords
+ sentences = map(lambda s: filter(lambda token: token not in stopWords, s), sentences)
+ return chain(* sentences)
+