corpus_statistic.py
10 KB
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
import corpus2
import codecs, os, sys, argparse
from npsemrel.carrot.db import db
from collections import defaultdict
def make_parser():
desc = 'Narzedzie generujace statystyke korpusu (liczba znaczen przypadajaca na slowa).'
parser = argparse.ArgumentParser(description = desc)
parser.add_argument('-i', '--index-doc', dest = 'index_doc', required = True)
parser.add_argument('-r', '--result-filename', dest = 'result_filename', required = True)
parser.add_argument('-d', '--db-config', dest = 'db_config', required = True)
parser.add_argument('-t', '--tagset', dest = 'tagset', default = 'nkjp')
parser.add_argument('-S', '--sentence', dest = 'sentence', action = 'store_true', required = False)
parser.add_argument('-m', '--manual-senses-statistic', dest = 'manual_senses_statistic', action = 'store_true', required = False)
return parser
def convert_to_num_pos(pl_pos):
noun_pl_pos = ['subst', 'depr', 'ger']
adj_pl_pos = ['adj', 'adja', 'adjp', 'adjc']
verb_pl_pos = ['fin', 'bedzie', 'praet', 'impt', \
'inf', 'pcon', 'pant', 'imps', \
'winien', 'pred', 'pact', 'ppas', 'pred']
pos_int = None
if pl_pos in noun_pl_pos:
pos_int = 2
elif pl_pos in adj_pl_pos:
pos_int = 4
elif pl_pos in verb_pl_pos:
pos_int = 1
return pos_int
def get_number_of_senses(lemma, pos_int, dbconnection):
query = 'SELECT LU.lemma, LU.pos, UAS.SYN_ID ' \
'FROM lexicalunit LU ' \
'JOIN unitandsynset UAS ON (LU.id = UAS.LEX_ID) ' \
'WHERE LU.lemma = BINARY "' + lemma + '" and LU.pos = ' + str(pos_int) + ';'
cursor = dbconnection.cursor()
cursor.execute(query)
return len(cursor.fetchall())
def make_statistic(corpus_index_file, result_file, tagset, dbconnection, is_sentence):
statistic_dict = {}
max_num_of_syn = 0
full_pos_mask = corpus2.get_attribute_mask(tagset, '')
with open(corpus_index_file, 'rt') as corpidx:
for corpfile in corpidx:
corpfile_path = os.path.join(os.path.dirname(corpus_index_file), corpfile).strip()
print >> sys.stderr, 'Reading:', corpfile_path
try:
cclreader = corpus2.CclRelReader(tagset, corpfile_path, corpfile_path)
document = cclreader.read()
statistic_dict[corpfile] = {}
for paragraph in document.paragraphs():
for sentence in paragraph.sentences():
statistic_dict[corpfile][sentence.id()] = {}
for token in sentence.tokens():
# Lemma
lemma = str(token.get_preferred_lexeme(tagset).lemma())
# POS
tag = token.get_preferred_lexeme(tagset).tag()
pos_mask = tag.get_masked(full_pos_mask)
pos_int = convert_to_num_pos(tagset.tag_to_symbol_string(pos_mask))
if not pos_int:
print >> sys.stderr, 'Niepoprawny POS dla lematu', lemma, '!'
continue
# Number of senses
num_of_syn = get_number_of_senses(lemma, pos_int, dbconnection)
if statistic_dict[corpfile][sentence.id()].has_key(num_of_syn):
statistic_dict[corpfile][sentence.id()][num_of_syn] += 1
else:
statistic_dict[corpfile][sentence.id()][num_of_syn] = 1
if num_of_syn > max_num_of_syn:
max_num_of_syn = num_of_syn
except Exception, e:
print >> sys.stderr, 'Error: ', e
with codecs.open(result_file, 'wt') as outfile:
if is_sentence:
num_of_syn_list = [0] * (max_num_of_syn + 1)
num_of_syn_str = ';'.join(str(i) for i in xrange(max_num_of_syn + 1))
outfile.write('Nazwa dokumentu;Numer zdania;%s\n' % num_of_syn_str)
for corpfile, sentence_dict in statistic_dict.iteritems():
for sentence, num_of_syn_dict in sentence_dict.iteritems():
for num_of_syn, num_of_lemmas in enumerate(num_of_syn_list):
num_of_syn_list[num_of_syn] = num_of_syn_dict[num_of_syn] if num_of_syn_dict.has_key(num_of_syn) else 0
num_of_syn_str = ';'.join(str(num_of_lemmas) for num_of_lemmas in num_of_syn_list)
outfile.write('%s;%s;%s\n' % (corpfile.strip(), sentence, num_of_syn_str))
else:
num_of_syn_str = ';'.join(str(i) for i in xrange(max_num_of_syn + 1))
outfile.write('Nazwa dokumentu;%s\n' % num_of_syn_str)
for corpfile, sentence_dict in statistic_dict.iteritems():
num_of_syn_list = [0] * (max_num_of_syn + 1)
for num_of_syn, num_of_lemmas in enumerate(num_of_syn_list):
for sentence, num_of_syn_dict in sentence_dict.iteritems():
if num_of_syn_dict.has_key(num_of_syn):
num_of_syn_list[num_of_syn] += num_of_syn_dict[num_of_syn]
num_of_syn_str = ';'.join(str(num_of_lemmas) for num_of_lemmas in num_of_syn_list)
outfile.write('%s;%s\n' % (corpfile.strip(), num_of_syn_str))
def make_manual_senses_statistic(corpus_index_file, result_file, tagset, dbconnection, is_sentence):
ann_dict = make_anotation_dictionary(dbconnection)
manual_statistic_dict = {}
full_pos_mask = corpus2.get_attribute_mask(tagset, '')
with open(corpus_index_file, 'rt') as corpidx:
for corpfile in corpidx:
corpfile_path = os.path.join(os.path.dirname(corpus_index_file), corpfile).strip()
print >> sys.stderr, 'Reading:', corpfile_path
try:
cclreader = corpus2.CclRelReader(tagset, corpfile_path, corpfile_path)
document = cclreader.read()
manual_statistic_dict[corpfile] = {}
for paragraph in document.paragraphs():
for sentence in paragraph.sentences():
manual_statistic_dict[corpfile][sentence.id()] = defaultdict(set)
for token in sentence.tokens():
# Manual sense
md = token.get_metadata()
if md:
attribs = md.attributes()
for attr_k, attr_v in attribs.iteritems():
if attr_k.startswith('sense:wsd_'):
if not ann_dict.has_key(attr_v):
print >> sys.stderr, 'Brak klucza %s w PLWN!' % (attr_v)
continue
# Lemma
lemma = str(token.get_preferred_lexeme(tagset).lemma())
# POS
tag = token.get_preferred_lexeme(tagset).tag()
pos_mask = tag.get_masked(full_pos_mask)
pos_int = convert_to_num_pos(tagset.tag_to_symbol_string(pos_mask))
if not pos_int:
print >> sys.stderr, 'Niepoprawny POS dla lematu', lemma, '!'
continue
manual_statistic_dict[corpfile][sentence.id()][(lemma, pos_int)].add(attr_v)
except Exception, e:
print >> sys.stderr, 'Error: ', e
statistic_dict = {}
max_num_of_syn = 0
for corpfile, sentence_dict in manual_statistic_dict.iteritems():
statistic_dict[corpfile] = {}
for sentence, lemma_pos_int_dict in sentence_dict.iteritems():
statistic_dict[corpfile][sentence] = {}
for manual_senses_set in lemma_pos_int_dict.itervalues():
num_of_syn = len(manual_senses_set)
if statistic_dict[corpfile][sentence].has_key(num_of_syn):
statistic_dict[corpfile][sentence][num_of_syn] += 1
else:
statistic_dict[corpfile][sentence][num_of_syn] = 1
if num_of_syn > max_num_of_syn:
max_num_of_syn = num_of_syn
with codecs.open(result_file, 'wt') as outfile:
if is_sentence:
num_of_syn_list = [0] * (max_num_of_syn + 1)
num_of_syn_str = ';'.join(str(i) for i in xrange(max_num_of_syn + 1))
outfile.write('Nazwa dokumentu;Numer zdania;%s\n' % num_of_syn_str)
for corpfile, sentence_dict in statistic_dict.iteritems():
for sentence, num_of_syn_dict in sentence_dict.iteritems():
for num_of_syn, num_of_lemmas in enumerate(num_of_syn_list):
num_of_syn_list[num_of_syn] = num_of_syn_dict[num_of_syn] if num_of_syn_dict.has_key(num_of_syn) else 0
num_of_syn_str = ';'.join(str(num_of_lemmas) for num_of_lemmas in num_of_syn_list)
outfile.write('%s;%s;%s\n' % (corpfile.strip(), sentence, num_of_syn_str))
else:
num_of_syn_str = ';'.join(str(i) for i in xrange(max_num_of_syn + 1))
outfile.write('Nazwa dokumentu;%s\n' % num_of_syn_str)
for corpfile, sentence_dict in statistic_dict.iteritems():
num_of_syn_list = [0] * (max_num_of_syn + 1)
for num_of_syn, num_of_lemmas in enumerate(num_of_syn_list):
for sentence, num_of_syn_dict in sentence_dict.iteritems():
if num_of_syn_dict.has_key(num_of_syn):
num_of_syn_list[num_of_syn] += num_of_syn_dict[num_of_syn]
num_of_syn_str = ';'.join(str(num_of_lemmas) for num_of_lemmas in num_of_syn_list)
outfile.write('%s;%s\n' % (corpfile.strip(), num_of_syn_str))
def make_key(comment):
return comment.replace('WSD', '').replace(' ', '').replace('#', '-').encode('utf-8')
def make_anotation_dictionary(dbconnection):
ann_dict = defaultdict(set)
print >> sys.stderr, 'Getting WSD comments from DB...',
query = "SELECT SYN.comment, SYN.id " \
"FROM synset SYN " \
"WHERE SYN.comment LIKE '%wsd%';"
cursor = dbconnection.cursor()
cursor.execute(query)
for row in cursor.fetchall():
comments = row[0].split(';')[0].split(',')
synset_id = int(row[1])
for comment in comments:
comment = make_key(comment)
ann_dict[comment].add(synset_id)
print >> sys.stderr, ' Done!'
return ann_dict
def main(argv = None):
parser = make_parser()
args = parser.parse_args(argv)
tagset = corpus2.get_named_tagset(args.tagset)
print >> sys.stderr, 'Connecting to DB...',
dbcon = db.DB()
dbconnection = dbcon.connect(args.db_config)
if not dbconnection:
print >> sys.stderr, 'Cannot connect to DB!'
exit(1)
print >> sys.stderr, ' Done!'
if args.manual_senses_statistic:
make_manual_senses_statistic(args.index_doc, args.result_filename, tagset, dbconnection, args.sentence)
else:
make_statistic(args.index_doc, args.result_filename, tagset, dbconnection, args.sentence)
if __name__ == '__main__':
main()