format_es.py
Go to the documentation of this file.
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright 2017 Mycroft AI Inc.
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 #
17 """
18 Format functions for castillian (es-es)
19 
20 """
21 from mycroft.util.lang.format_common import convert_to_mixed_fraction
22 
23 NUM_STRING_ES = {
24  0: 'cero',
25  1: 'uno',
26  2: 'dos',
27  3: 'tres',
28  4: 'cuatro',
29  5: 'cinco',
30  6: 'seis',
31  7: 'siete',
32  8: 'ocho',
33  9: 'nueve',
34  10: 'diez',
35  11: 'once',
36  12: 'doce',
37  13: 'trece',
38  14: 'catorce',
39  15: 'quince',
40  16: 'dieciséis',
41  17: 'diecisete',
42  18: 'dieciocho',
43  19: 'diecinueve',
44  20: 'veinte',
45  30: 'treinta',
46  40: 'cuarenta',
47  50: 'cincuenta',
48  60: 'sesenta',
49  70: 'setenta',
50  80: 'ochenta',
51  90: 'noventa'
52 }
53 
54 FRACTION_STRING_ES = {
55  2: 'medio',
56  3: 'tercio',
57  4: 'cuarto',
58  5: 'quinto',
59  6: 'sexto',
60  7: 'séptimo',
61  8: 'octavo',
62  9: 'noveno',
63  10: 'décimo',
64  11: 'onceavo',
65  12: 'doceavo',
66  13: 'treceavo',
67  14: 'catorceavo',
68  15: 'quinceavo',
69  16: 'dieciseisavo',
70  17: 'diecisieteavo',
71  18: 'dieciochoavo',
72  19: 'diecinueveavo',
73  20: 'veinteavo'
74 }
75 
76 
77 def nice_number_es(number, speech, denominators):
78  """ Spanish helper for nice_number
79 
80  This function formats a float to human understandable functions. Like
81  4.5 becomes "4 y medio" for speech and "4 1/2" for text
82 
83  Args:
84  number (int or float): the float to format
85  speech (bool): format for speech (True) or display (False)
86  denominators (iter of ints): denominators to use, default [1 .. 20]
87  Returns:
88  (str): The formatted string.
89  """
90  strNumber = ""
91  whole = 0
92  num = 0
93  den = 0
94 
95  result = convert_to_mixed_fraction(number, denominators)
96 
97  if not result:
98  # Give up, just represent as a 3 decimal number
99  whole = round(number, 3)
100  else:
101  whole, num, den = result
102 
103  if not speech:
104  if num == 0:
105  strNumber = '{:,}'.format(whole)
106  strNumber = strNumber.replace(",", " ")
107  strNumber = strNumber.replace(".", ",")
108  return strNumber
109  else:
110  return '{} {}/{}'.format(whole, num, den)
111  else:
112  if num == 0:
113  # if the number is not a fraction, nothing to do
114  strNumber = str(whole)
115  strNumber = strNumber.replace(".", ",")
116  return strNumber
117  den_str = FRACTION_STRING_ES[den]
118  # if it is not an integer
119  if whole == 0:
120  # if there is no whole number
121  if num == 1:
122  # if numerator is 1, return "un medio", for example
123  strNumber = 'un {}'.format(den_str)
124  else:
125  # else return "cuatro tercios", for example
126  strNumber = '{} {}'.format(num, den_str)
127  elif num == 1:
128  # if there is a whole number and numerator is 1
129  if den == 2:
130  # if denominator is 2, return "1 y medio", for example
131  strNumber = '{} y {}'.format(whole, den_str)
132  else:
133  # else return "1 y 1 tercio", for example
134  strNumber = '{} y 1 {}'.format(whole, den_str)
135  else:
136  # else return "2 y 3 cuarto", for example
137  strNumber = '{} y {} {}'.format(whole, num, den_str)
138  if num > 1 and den != 3:
139  # if the numerator is greater than 1 and the denominator
140  # is not 3 ("tercio"), add an s for plural
141  strNumber += 's'
142 
143  return strNumber
144 
145 
146 def pronounce_number_es(num, places=2):
147  """
148  Convert a number to it's spoken equivalent
149 
150  For example, '5.2' would return 'cinco coma dos'
151 
152  Args:
153  num(float or int): the number to pronounce (under 100)
154  places(int): maximum decimal places to speak
155  Returns:
156  (str): The pronounced number
157  """
158  if abs(num) >= 100:
159  # TODO: Soporta a números por encima de 100
160  return str(num)
161 
162  result = ""
163  if num < 0:
164  result = "menos "
165  num = abs(num)
166 
167  # del 21 al 29 tienen una pronunciación especial
168  if 20 <= num <= 29:
169  tens = int(num-int(num) % 10)
170  ones = int(num - tens)
171  result += NUM_STRING_ES[tens]
172  if ones > 0:
173  result = result[:-1]
174  # a veinte le quitamos la "e" final para construir los
175  # números del 21 - 29. Pero primero tenemos en cuenta
176  # las excepciones: 22, 23 y 26, que llevan tilde.
177  if ones == 2:
178  result += "idós"
179  elif ones == 3:
180  result += "itrés"
181  elif ones == 6:
182  result += "iséis"
183  else:
184  result += "i" + NUM_STRING_ES[ones]
185  elif num >= 30: # de 30 en adelante
186  tens = int(num-int(num) % 10)
187  ones = int(num - tens)
188  result += NUM_STRING_ES[tens]
189  if ones > 0:
190  result += " y " + NUM_STRING_ES[ones]
191  else:
192  result += NUM_STRING_ES[int(num)]
193 
194  # Deal with decimal part, in spanish is commonly used the comma
195  # instead the dot. Decimal part can be written both with comma
196  # and dot, but when pronounced, its pronounced "coma"
197  if not num == int(num) and places > 0:
198  result += " coma"
199  place = 10
200  while int(num*place) % 10 > 0 and places > 0:
201  result += " " + NUM_STRING_ES[int(num*place) % 10]
202  place *= 10
203  places -= 1
204  return result
205 
206 
207 def nice_time_es(dt, speech=True, use_24hour=False, use_ampm=False):
208  """
209  Format a time to a comfortable human format
210 
211  For example, generate 'cinco treinta' for speech or '5:30' for
212  text display.
213 
214  Args:
215  dt (datetime): date to format (assumes already in local timezone)
216  speech (bool): format for speech (default/True) or display (False)=Fal
217  use_24hour (bool): output in 24-hour/military or 12-hour format
218  use_ampm (bool): include the am/pm for 12-hour format
219  Returns:
220  (str): The formatted time string
221  """
222  if use_24hour:
223  # e.g. "03:01" or "14:22"
224  string = dt.strftime("%H:%M")
225  else:
226  if use_ampm:
227  # e.g. "3:01 AM" or "2:22 PM"
228  string = dt.strftime("%I:%M %p")
229  else:
230  # e.g. "3:01" or "2:22"
231  string = dt.strftime("%I:%M")
232  if string[0] == '0':
233  string = string[1:] # strip leading zeros
234 
235  if not speech:
236  return string
237 
238  # Generate a speakable version of the time
239  speak = ""
240  if use_24hour:
241  # Tenemos que tener en cuenta que cuando hablamos en formato
242  # 24h, no hay que especificar ninguna precisión adicional
243  # como "la noche", "la tarde" o "la mañana"
244  # http://lema.rae.es/dpd/srv/search?id=YNoTWNJnAD6bhhVBf9
245  if dt.hour == 1:
246  speak += "la una"
247  else:
248  speak += "las " + pronounce_number_es(dt.hour)
249 
250  # las 14:04 son "las catorce cero cuatro"
251  if dt.minute < 10:
252  speak += " cero " + pronounce_number_es(dt.minute)
253  else:
254  speak += " " + pronounce_number_es(dt.minute)
255 
256  else:
257  # Prepare for "tres menos cuarto" ??
258  if dt.minute == 35:
259  minute = -25
260  hour = dt.hour + 1
261  elif dt.minute == 40:
262  minute = -20
263  hour = dt.hour + 1
264  elif dt.minute == 45:
265  minute = -15
266  hour = dt.hour + 1
267  elif dt.minute == 50:
268  minute = -10
269  hour = dt.hour + 1
270  elif dt.minute == 55:
271  minute = -5
272  hour = dt.hour + 1
273  else:
274  minute = dt.minute
275  hour = dt.hour
276 
277  if hour == 0 or hour == 12:
278  speak += "las doce"
279  elif hour == 1 or hour == 13:
280  speak += "la una"
281  elif hour < 13:
282  speak = "las " + pronounce_number_es(hour)
283  else:
284  speak = "las " + pronounce_number_es(hour-12)
285 
286  if minute != 0:
287  # las horas especiales
288  if minute == 15:
289  speak += " y cuarto"
290  elif minute == 30:
291  speak += " y media"
292  elif minute == -15:
293  speak += " menos cuarto"
294  else: # seis y nueve. siete y veinticinco
295  if minute > 0:
296  speak += " y " + pronounce_number_es(minute)
297  else: # si son las siete menos veinte, no ponemos la "y"
298  speak += " " + pronounce_number_es(minute)
299 
300  # si no especificamos de la tarde, noche, mañana, etc
301  if minute == 0 and not use_ampm:
302  # 3:00
303  speak += " en punto"
304 
305  if use_ampm:
306  # "de la noche" es desde que anochece hasta medianoche
307  # así que decir que es desde las 21h es algo subjetivo
308  # en España a las 20h se dice "de la tarde"
309  # en castellano, las 12h es de la mañana o mediodía
310  # así que diremos "de la tarde" a partir de las 13h.
311  # http://lema.rae.es/dpd/srv/search?id=YNoTWNJnAD6bhhVBf9
312  if hour >= 0 and hour < 6:
313  speak += " de la madrugada"
314  elif hour >= 6 and hour < 13:
315  speak += " de la mañana"
316  elif hour >= 13 and hour < 21:
317  speak += " de la tarde"
318  else:
319  speak += " de la noche"
320  return speak
def pronounce_number_es(num, places=2)
Definition: format_es.py:146
def nice_number_es(number, speech, denominators)
Definition: format_es.py:77
def nice_time_es(dt, speech=True, use_24hour=False, use_ampm=False)
Definition: format_es.py:207
def convert_to_mixed_fraction(number, denominators)


mycroft_ros
Author(s):
autogenerated on Mon Apr 26 2021 02:35:40