forked from nimotsu/speech-recognition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtext.py
82 lines (75 loc) · 1.73 KB
/
text.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
import torch
import num2words
import re
class TextProcess:
def __init__(self):
char_map_str = """
' 0
<SPACE> 1
a 2
b 3
c 4
d 5
e 6
f 7
g 8
h 9
i 10
j 11
k 12
l 13
m 14
n 15
o 16
p 17
q 18
r 19
s 20
t 21
u 22
v 23
w 24
x 25
y 26
z 27
"""
self.char_map = {}
self.index_map = {}
for line in char_map_str.strip().split('\n'):
ch, index = line.split()
self.char_map[ch] = int(index)
self.index_map[int(index)] = ch
self.index_map[1] = ' '
def text_to_int_sequence(self, text):
""" Use a character map and convert text to an integer sequence """
int_sequence = []
for c in text:
if c == ' ':
ch = self.char_map['<SPACE>']
else:
ch = self.char_map[c]
int_sequence.append(ch)
return int_sequence
def int_to_text_sequence(self, labels):
""" Use a character map and convert integer labels to an text sequence """
string = []
for i in labels:
string.append(self.index_map[i])
return ''.join(string).replace('<SPACE>', ' ')
# methods to clean text
def clean_text(self, text):
text = text.lower()
text = self.remove_punctuations(text)
text = self.convert_year_to_words(text)
text = self.convert_num_to_words(text)
text = text.replace('-', ' ')
return text
def convert_year_to_words(self, text):
text = ' '.join([num2words.num2words(i, to='year') if (i.isdigit() & (len(i) == 4)) else i for i in text.split()])
return text
def convert_num_to_words(self, text):
text = ' '.join([num2words.num2words(i) if i.isdigit() else i for i in text.split()])
return text
def remove_punctuations(self, text):
text = re.sub(r'[^\w\s]', ' ', text)
return text