-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpreprocess.py
139 lines (120 loc) · 4.5 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
import argparse
import os
import string
from nltk.tokenize import sent_tokenize
from nltk.tokenize import StanfordTokenizer, wordpunct_tokenize
from nltk.corpus import stopwords
from utils import loadRule, ProgressBar, getFilenames, getContentAndHighlight, saveContentandHighlights
verbose = os.environ.get('VERBOSE', 'no') == 'yes'
debug = os.environ.get('DEBUG', 'no') == 'yes'
def sentTokenize(lines):
'''
Tokenize the line in lines into sentences
:param lines: list of paragraphs
:return: list of sentence
'''
lstSents = []
for line in lines:
sents = sent_tokenize(line)
lstSents += sents
return lstSents
def wordTokenize(sents):
'''
Tokenize the sentence in sents into words
:param sents: list of sentences
:return: list of sentences which words are separated by one whitespace
'''
#tokenizer = StanfordTokenizer()
result = [wordpunct_tokenize(sent) for sent in sents]
result = [' '.join([word for word in sent]) for sent in result]
return result
def removePunct(sents):
'''
Remove the punctuations in sentence
:param sents: list of sentences
:return: list of sentences which not contain any punctuations.
'''
punctuation = list(string.punctuation)
unicodeMap = dict((ord(char), None) for char in string.punctuation)
result = []
for sent in sents:
words = sent.split()
words = [word for word in words if word not in punctuation]
words = [word.translate(unicodeMap) for word in words]
result.append(u' '.join([word for word in words if word != '']))
return result
def removeStopwords(sents):
'''
Remove stop-words in sentences
:param sents: list of sentences
:return: list of sentences which not contain any punctuations.
'''
lstStopwords = stopwords.words('english')
result = []
for sent in sents:
words = sent.split()
words = [word for word in words if word not in lstStopwords]
result.append(u' '.join([word for word in words]))
return result
def preprocess(content, highlights, config):
'''
Preprocess the dataset:
./ Sentence segmentation
./ Word segmentation
./ ... (Update lated)
:param content: list of paragraph in the content part
:param highlights: list of highlights
:param config: dict of config. E.g. dict['remove stopword'] = True, ...
:return: tuple (content, highlights) are processed
'''
#TODO: Tokenize list of paragraphs in content part into list of sentences
content = sentTokenize(content)
#TODO: Tokenize words in sentences
content = wordTokenize(content)
highlights = wordTokenize(highlights)
#TODO: Convert some abbreviation to standard format (more details see in abbreviation.txt)
rules = loadRule('abbreviation.txt')
for rule in rules:
content = [sent.replace(rule[0], rule[1]) for sent in content]
highlights = [sent.replace(rule[0], rule[1]) for sent in highlights]
#TODO: Remove punctuations
if config['remove punct']:
content = removePunct(content)
highlights = removePunct(highlights)
# TODO: Remove stop-word
if config['remove stopword']:
content = removeStopwords(content)
highlights = removeStopwords(highlights)
return (content, highlights)
def main():
#TODO: Parse the list of arguments
parser = argparse.ArgumentParser()
parser.add_argument('-indir', required=True, type=str)
parser.add_argument('-outdir', required=True, type=str)
args = parser.parse_args()
path2InDir = args.indir
path2OutDir = args.outdir
if not os.path.exists(path2OutDir):
os.mkdir(path2OutDir)
print "Preprocessing ..."
confPreprocess = {}
confPreprocess['remove stopword'] = False
confPreprocess['remove punct'] = True
nbSkipFile = 0
lstErrors = []
lstFiles = getFilenames(path2InDir)
progress_bar = ProgressBar(len(lstFiles))
for filename in lstFiles:
fullPath = os.path.join(path2InDir, filename)
try:
content, highlights = getContentAndHighlight(fullPath)
except ValueError:
nbSkipFile += 1
continue
content, highlights = preprocess(content, highlights, confPreprocess)
saveContentandHighlights(content, highlights, os.path.join(path2OutDir, filename + '.pre'))
progress_bar.Increment()
print 'NOTE: We skip %d file because length of content or highlights is zero.' % nbSkipFile
print 'DONE!'
if __name__ == '__main__':
main()