-
Notifications
You must be signed in to change notification settings - Fork 0
/
reaccentue.py
executable file
·170 lines (146 loc) · 5.49 KB
/
reaccentue.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
#!/usr/bin/env python
import sys
import os.path
import re
import select
import csv
import pickle
import gzip
from unidecode import unidecode
def add_dico(mot, dico):
if mot < 'A':
return
maj = unidecode(mot).upper()
if maj in dico:
if mot not in dico[maj]:
dico[maj].append(mot)
else:
dico[maj] = [mot]
def load_word(mot, dico, affixes):
m = re.sub(r'/.*', '', mot)
add_dico(m, dico)
rules = re.sub(r'.*/', '', mot)
while rules != '':
rule = rules[0:2]
rules = rules[2:]
if rule in affixes:
if affixes[rule]['type'] == 'SFX':
for r in affixes[rule]['rules']:
if re.search(r[4]+'$', m):
suffixe = re.sub(r'/.*', '', re.sub(r[2]+'$', r[3], m))
if suffixe != m:
add_dico(suffixe, dico)
if '/' in r[3]:
load_word(re.sub(r[2]+'$', r[3], m), dico, affixes)
if affixes[rule]['type'] == 'PFX':
for r in affixes[rule]['rules']:
if re.search('^'+r[4], m):
if '/' in r[3]:
add_dico(re.sub(r'/.*', '', re.sub('^'+r[2],
r[3], m)), dico)
load_word(re.sub('^'+r[2], r[3], m), dico, affixes)
elif re.sub('^'+r[2], r[3], m) != m:
add_dico(re.sub('^'+r[2], r[3], m), dico)
print('-> ', re.sub('^'+r[2], r[3], m), r)
def load_dico(fichier, dico):
"Charge le dictionnaire MAJUSCULE > minuscules accentuées"
# charge les définitions des suffixes (SFX)
affixes = dict()
try:
with open(fichier+'.aff', mode='r') as affix:
for aff in affix:
af = aff.split()
if len(af) == 4 and af[0] in ['SFX']: # header
affixes[af[1]] = {'type': af[0], 'cross_product': af[2],
'rules': []}
if len(af) > 4 and af[0] in ['SFX']: # rules
if af[2] == '0':
af[2] = ''
if af[3][0] == '0':
af[3] = af[3][1:]
affixes[af[1]]['rules'].append(af)
except:
pass
# charge le contenu du dictionaire en appliquant préfixes/suffixes
with open(fichier+'.dic', mode='r') as dicco:
for mot in dicco:
mot = mot.replace('\n', '')
load_word(mot, dico, affixes)
return dico
def reduce_dico():
# on élimine les entrées uniques sans accent
global dico
dico = {key:val for key, val in dico.items()
if len(val)>1 or val[0]!=unidecode(val[0])}
# on complète avec les fréquences de doublets avec mot précédent
with gzip.open('dico/freq5.pz', 'rb') as cache:
freq = pickle.load(cache)
for f in freq:
mots = unidecode(f).upper().split()
if len(mots)>1 and mots[1] in dico:
dico[f] = freq[f]
def reaccentue(maj):
prev = None
for mot in maj.split():
if mot.lower() in articles:
maj = maj.replace(mot, mot.lower())
elif mot.upper() in dico and len(dico[mot.upper()]) == 1:
maj = maj.replace(mot, dico[mot.upper()][0].capitalize())
else:
mm = None
if prev != None and mot.upper() in dico:
f = 0
for m in dico[mot.upper()]:
ml = m.lower()
if prev+' '+ml in dico:
if dico[prev+' '+ml] > f:
f = dico[prev+' '+ml]
mm = m
if mm is None:
mm = mot
maj = maj.replace(mot, mm.lower().capitalize())
prev = mot.lower()
return maj
dico = None
freq = None
try:
if (os.path.getmtime('dico/fr-toutesvariantes.dic') <
os.path.getmtime('dico/cache.pz')):
with gzip.open('dico/cache.pz', 'rb') as dico_cache:
dico = pickle.load(dico_cache)
except:
pass
if dico is None:
dico = dict()
dico = load_dico('dico/fr-toutesvariantes', dico)
dico = load_dico('dico/complements', dico)
reduce_dico()
with gzip.open('dico/cache.pz', 'wb') as dico_cache:
pickle.dump(dico, dico_cache)
articles = ['le', 'la', 'les',
'un', 'une', 'des',
'à', 'au', 'aux',
'du', 'de',
'et', 'ou']
if __name__ == "__main__":
if len(sys.argv) == 1:
if select.select([sys.stdin, ], [], [], 0.0)[0]:
lines = sys.stdin.readlines()
for l in lines:
print(reaccentue(l.replace('\n', '')))
else:
print("""Usage: reaccentue.py texte ou fichier
reaccentue.py 'BOULEVARD DU MARECHAL JEAN MARIE DE LATTRE DE TASSIGNY'
reaccentue.py fichier.csv nom_colonne""")
else:
if bool(re.search('.csv$', sys.argv[1])):
with open(sys.argv[1], 'r') as in_file:
csv_in = csv.DictReader(in_file)
csv_out = csv.DictWriter(sys.stdout,
fieldnames=csv_in.fieldnames)
csv_out.writerow(dict((fn, fn) for fn in csv_in.fieldnames))
for row in csv_in:
row[sys.argv[2]] = reaccentue(row[sys.argv[2]])
csv_out.writerow(row)
else:
print(reaccentue(sys.argv[1]))