ev3dev and portuguese

Using ev3dev and python to speak a few words in english in english is very easy:

from ev3dev2.sound import Sound
sound = Sound()
sound.speak('Good morning')

Making it speak portuguese words is also easy:

from ev3dev2.sound import Sound
sound = Sound()
sound.speak('Bom dia', espeak_opts='-v pt')

not a great pronounce but still understandable.

Problems started when trying to speak sentences written with portuguese characters like “Olá” (“Hello”)

sound.speak('Olá', espeak_opts='-v pt')

it generates an error similar to this:

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

my ev3dev installation wasn’t configured to understand non-ASCII characters so a quick setting at the command line corrected this:

$ export LC_ALL="en_US.UTF-8"
$ export LC_CTYPE="en_US.UTF-8"

Now I wanted to speak the current date, like ‘Today is Friday 25 December” so I found ‘datetime’

from datetime import datetime as dt
import datetime

today = dt.today()
speech = today.strftime("%A") + ' ' + today.strftime("%-d") + ' ' + today.strftime("%B")
sound.speak('Today is ' + speech)

Great. At least in english. But how to do it in portuguese (i.e. ‘Hoje é Sexta 25 Dezembro”)? How to make today.strftime(“%A) return “Sexta” instead of “Friday”?
The trick is using ‘locale’:

from datetime import datetime as dt
import datetime
import locale

locale.setlocale(locale.LC_TIME, "pt_PT") 
today = dt.today()
speech = today.strftime("%A") + ' ' + today.strftime("%-d") + ' ' + today.strftime("%B")
sound.speak('Today is ' + speech)

And now another error:

locale.Error: unsupported locale setting

ev3dev doesn’t have Portuguse locale settings (we can check with ‘locale -a‘). So I needed to install them:

$ sudo dpkg-reconfigure locales

Deixe um comentário

O seu endereço de email não será publicado. Campos obrigatórios marcados com *