python logo


Category: Uncategorized

Save a dictionary to a file

How to make python save a dictionary to a file. These are small programs that allows you to create a dictionary and then, when running the program, it will create a file that contains the data in the original dictionary.

Given a dictionary such as:


dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

We can save it to one of these formats:

  • Comma seperated value file (.csv)
  • Json file (.json)
  • Text file (.txt)
  • Pickle file (.pkl)

You could also write to a SQLite database.

Related Course:

save dictionary as csv file

The csv module allows Python programs to write to and read from CSV (comma-separated value) files.

CSV is a common format used for exchanging data between applications. The module provides classes to represent CSV records and fields, and allows outputs to be formatted as CSV files.

In this format every value is separated between a comma, for instance like this:

Python,py,programming,
Bitmap,bmp,picture,
Sound,mp3,audio,

You can write it to a file with the csv module.

# load csv module
import csv

# define a dictionary with key value pairs
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

# open file for writing, "w" is writing
w = csv.writer(open("output.csv", "w"))

# loop over dictionary keys and values
for key, val in dict.items():

# write every key and value to file
w.writerow([key, val])


python-write-dictionary-to-csv The dictionary file (csv) can be opened in Google Docs or Excel

save dictionary to json file

Today, a JSON file has become more and more common to transfer data in the world. JSON (JavaScript Object Notation) is a lightweight data-interchange format.

JSON is easy for humans to read and write. It is easy for machines to parse and generate.

JSON is a text format that is completely language independent but uses conventions that are familiar to programmers of the C-family of languages, including C, C++, C#, Java, JavaScript, Perl, Python, and many others.

JSON was originally derived from the JavaScript scripting language, but it is not limited to any one programming language.

If you want to save a dictionary to a json file


# load json module
import json

# python dictionary with key value pairs
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

# create json object from dictionary
json = json.dumps(dict)

# open file for writing, "w"
f = open("dict.json","w")

# write json object to file
f.write(json)

# close file
f.close()

save dictionary to text file (raw, .txt)

The program below writes a dictionary to an text string. It uses the str() call to convert the dictionary to a text string. While it is easy to write as a text string, this format makes it harder to read the file.

You can save your dictionary to a text file using the code below:

# define dict
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

# open file for writing
f = open("dict.txt","w")

# write file
f.write( str(dict) )

# close file
f.close()

save dictionary to a pickle file (.pkl)

The pickle module may be used to save dictionaries (or other objects) to a file. The module can serialize and deserialize Python objects.

In Python, pickle is a built-in module that implements object serialization. It is both cross-platform and cross language, meaning that it can save and load objects between Python programs running on different operating systems, as well as between Python running on different platforms.

The pickle module is written entirely in Python, and is available in CPython implementations, such as Jython or IronPython. To enable the loading of pickles in other Python modules, pickle supports being executed from the command line.

The program below writes it to a pickle file.


# load pickle module
import pickle

# define dictionary
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

# create a binary pickle file
f = open("file.pkl","wb")

# write the python object (dict) to pickle file
pickle.dump(dict,f)

# close file
f.close()

Related Course: Python Crash Course: Master Python Programming

String-Methoden

Ein Beispiel für die Verwendung einer String-Methode:


s = "Hello World"
s = s.replace("World","Python")
Print(s)

Related Course:
Python Programming Bootcamp: Go from zero to hero

Übersicht
Python umfasst diese nützlichen Methoden zur String-Manipulation:



Methode mit Beschreibung
capitalize(Str)
Renditen erste Buchstabe großgeschrieben Zeichenfolge.
Count(Str)
Zählen Sie die Häufigkeit des Wortes str. Es kann auch auf Wörter angewendet werden: s.count("Hello")
find(Str)
Finden Sie die Position des ersten Vorkommens.
Index(Str)
Finden Sie die Position des ersten Vorkommens, Ausnahme wenn nicht gefunden.
isdecimal()
Gibt True zurück, wenn Zeichenfolge decimal ist.
isdigit()
Gibt True zurück, wenn String nur Ziffern enthält.
IsNumeric()
Gibt True zurück, wenn Zeichenfolge nur numerische enthält.
Lower()
Retouren-Zeichenfolge in Kleinbuchstaben.
len(Str)
Gibt die Länge von str zurück.
gross()
Retouren-Zeichenfolge in Großbuchstaben.
ersetzen Sie (alt, neu)
Das erste Argument ersetzt mit dem zweiten Argument.

Python IDEs

Ein Python-IDE installieren


Ein Integrierte Arbeitsumgebung (IDE) ist eine Softwareanwendung für die Programmierung. Neben einfachen Text-Bearbeitung haben sie alle Arten von Funktionen wie Syntax-highlighting, Code-Vervollständigung, Tabs, ein Klassenbrowser und vieles mehr.


Online Python-Interpreters


Die online Dolmetscher funktioniert möglicherweise nicht für alles aber funktioniert für die meisten Anfänger-Tutorials. Ich empfehle eine desktop-IDE oder das offizielle Python-Interpreter.


Übersicht über IDEs (Sie benötigen nur eins)


IDE Author Plattform Beschreibung Preis Herunterladen
PyCharm Jetbrains Windows, Mac OS X, Linux/UNIX Python IDE. Funktionen, einschließlich: Code-Vervollständigung, Code-Inspektionen, on-the-Fly Fehler hervorheben und Schnellkorrekturen € 89 / 1. Jahr. ($ 97,90) Download PyCharm 
Atom (+ Skript Plugin) GitHub Windows, Mac OS X, Linux/UNIX Python IDE. Sie müssen das Skript Plugin download nach der Installation von Atom. Kostenlos. Download Atom.
Pythonista OMZ:Software Apple iOS (iPhone, iPad) Eigenschaften umfassen: Syntax-highlighting, Code-Vervollständigung, interaktive Eingabeaufforderung, Standard und iOS-Module. 9 €. ($ 9,90) Download Pythonista.
Eclipse mit PyDev Aleks Totic Windows, Mac OS X, Linux/UNIX Eigenschaften umfassen: Syntax-Hervorhebung, Codeumgestaltung, grafische Debuggen und mehr. Free Herunterladen 
Eric Python IDE Detlev Offenbach Windows, Linux/UNIX Eigenschaften umfassen: Syntax-Hervorhebung, Auto-Vervollständigung, Klassenkatalog und mehr. Free Herunterladen 
Wing IDE Wingware Windows, Mac OS X, Linux/UNIX Merkmale: Syntax-Hervorhebung, Auto-Vervollständigung, Umgestaltung, Komponententests und Steuern Version. 45 $245 pro Benutzer / eine Lizenz. Herunterladen 
Komodo IDE Komodo Windows, Mac OS X, Linux/UNIX Merkmale: Syntax-Hervorhebung, Dokumentationsbrowser, Ausführen von Code in Zeile, schnelle Lesezeichen und mehr. € 40 bis € 223. ($99 auf $295). Herunterladen 
Skulpt Skulpt Web Python-interpreter Free Führen Sie Online 
Repl.it Amjad Masad, Haya Odeh, Faris Masad und Max Shawabkeh. Web Python-interpreter Free Führen Sie Online 
Ideone Ideone Web Python-interpreter Free Führen Sie Online 
CodePad Steven Hazel Web Python-interpreter Free Führen Sie Online 

Log functions in Python (Guide)

Log messages can indicate an event has executed.
You can use logging for these purposes:


  • debugging

  • informational messages

  • show warnings

  • show errors

  • show critical messages


The log method to use depends on the severity of the message. Debug messages can help you with programming your applications but are not severe.

Overview:

To use start logging, load the logging module with “import logging”.


import logging
logging.warning('File could not be opened')

We can use all the types of logging:


import logging
logging.debug('Debug message')
logging.info('Informational message')
logging.warning('Warning message')
logging.error('Error mesage')
logging.critical('Critical message')

Logging levels

You can add debug messages to your program, and on release change the logging level to information to hide them. It’s also recommended to save logging messages to a file:


logging.basicConfig(filename='program.log',level=logging.INFO)

To return to debugging mode, change to:


logging.basicConfig(filename='program.log',level=logging.DEBUG)

The standard level is warning.

Practical example

An example of using the log module below:


import logging

x = int(raw_input("Enter a number: "))

if x < 0:
logging.error('Error: x must be positive.')
exit(0)
else:
print("Starting calculation")
logging.info("Calculation started.")

 

How to write Comments in Python (Guide)

Comments can be added to Python programs, this makes your code easy to understand by others. A comment is human readable text that is not executed by Python.

It increases the readability of your code, comments are written for software developers. Comments are ignored by the Python interpreter

Python has several possibilities to add comments.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Python commenting

A single line comment can be added by using the hash (#) character. The hash (#) is added for every line that should be commented.

You can put any comment in the code:

# Show the world a message
print('Hello World')

If you use a modern Python IDE, it will highlight your comment in another color. Each comment is ignored by Python.

If a statement is put before the comment, the statement is run but the comment is ignored.

print("Run this")  # Ignore this

The code above will only show “Run this” in the terminal.

Python Mutliline Comments

Python does not have a way to add multiline comments with special characters.
A language like Java or C++ allows you to write multiline comments like this:

/* You can write
multiline comments
like this in C++ */

Then the whole block is ignored, but Python doesn’t have native multiline commenting support.

In Python you can create multiline comments like this:

# You can write
# multiline comments
# like this in Python

Another way to do this is using triple quotes ‘’’ characters, this is ignored by Python but officially that’s for documentation not comments.

'''
We can type multiple lines of commment
if we use the indicator.
'''

Why comments?

There are two main reasons to add comments to your code.

1) to make your own code more readable
2) to make your code understandable for others

Sometimes developers add notes or todo lists in their code.

As a developer you write a lot of code, and you may forget what a piece of code does. Commenting helps you increase your productivity.

Related Course: Python Programming Bootcamp: Go from zero to hero

Array find in Python

Arrays are usually referred to as lists. For convience, lets call them arrays in this article.

Python has a method to search for an element in an array, known as index().
We can find an index using:


x = ['p','y','t','h','o','n']
print(x.index('o'))

Arrays start with the index zero (0) in Python:

python-string Python character array

If you would run x.index(‘p’) you would get zero as output (first index).

Related course:

Array duplicates: If the array contains duplicates, the index() method will only return the first element.

Find multiple occurences

If you want multiple to find multiple occurrences of an element, use the lambda function below.


get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]

Find in string arrays

To find an element in a string array use:


x = ["Moon","Earth","Jupiter"]
print(x.index("Earth"))

You could use this code if you want to find multiple occurrences:



x = ["Moon","Earth","Jupiter","Neptune","Earth","Venus"]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes("Earth",x))


Find in numeric array

The index method works on numeric arrays too:


x = [5,1,7,0,3,4]
print(x.index(7))

To find multiple occurrences you can use this lambda function:



x = [5,1,7,0,3,4,5,3,2,6,7,3,6]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes(7,x))


Round number

The round(x,n) method returns a rounded number x to n decimals.
The method has these arguments:

  • x : number to round
  • n : number of decimals

An example of using the method below (it returns 1.06):


#!/usr/bin/python

x = round(1.5056, 2)
print(x)

Related Course:
Python Programming Bootcamp: Go from zero to hero

Rounding errors

You would probably round 1.85, 2.85, 3.85, 4.85 and 5.85 up, right? If you try this in a computer you won’t get that result:


print( round(1.85, 1) )
print( round(2.85, 1) )
print( round(3.85, 1) )
print( round(4.85, 1) )
print( round(5.85, 1) )
print( round(6.85, 1) )

Decimal places are not exact in a computer system, which uses base 2 instead of base 10. You can view the value that round returns with the Decimal module:


#!/usr/bin/python
from decimal import Decimal

print( Decimal(1.85) )
print( Decimal(2.85) )
print( Decimal(3.85) )
print( Decimal(4.85) )
print( Decimal(5.85) )
print( Decimal(6.85) )

It will print the values that are stored in the computer memory. You might be surprised. These numbers are called floating points.

Round to the nearest number


 
Round up
If you want all floating points to be rounded up, use the math.ceil(x) method instead:


#!/usr/bin/python
import math

print( math.ceil(2.5) )

Round down
If you want a floating point to be rounded down, you could use


#!/usr/bin/python
import math

print( math.floor(2.5) )

Python time.sleep() - Add Time Delays

To make a Python program delay (pause execution), use the sleep(seconds) method.  which can be found in the time module.
The time module provides many time related functionality like getting the current time, converting epoch time and others.

Related Course:
Python Programming Bootcamp: Go from zero to hero

The time.sleep pauses execution, making the program wait for the defined time. The time to wait (sleep) is defined in seconds. If you don’t want the program to completely freeze use threading instead.


import time
time.sleep(5) # Wait for 5 seconds

The time.sleep(sec) method supports floating point numbers, meaning you can make it wait half a second too


import time
time.sleep(0.100) # Wait for 100 milliseconds

A simple countdown timer from 5:


import time

seconds = 5
while seconds > 0:
print(seconds)
time.sleep(1)
seconds = seconds - 1

Accuracy


The time.sleep(seconds) is not real time. The accuracy depends on the operating system, sometimes it may be off in terms of milliseconds.

To wait about 50 milliseconds:


Python 2.7.11+ (default, Apr 17 2016, 14:00:29)
[GCC 5.3.1 20160413] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from time import sleep
>>> sleep(0.05)

You won’t get exactly 50ms if you rely on the sleep method.

Most PC machines have hardware limits in the 1-10ms range, regardless of operating system. To the operating system, time.sleep() just means a hint. It’s not a good timing mechanism, but good enough for most applications.

Operating systems may have different implementations, causing a difference in time.

time.sleep accuracy
(Image from Stackoverflow)

For higher accuracy, you need dedicated hardware (embedded system) to keep accurate time on the milliseconds level.






Speech engines with python tutorial

Text To Speech (TTS) Text To Speech (TTS)

A computer system used to create artificial speech is called a speech synthesizer, and can be implemented in software or hardware products.

A text-to-speech (TTS) system converts normal language text into speech. How can we use speech synthesis in Python?

Related courses:

Pyttsx


Pyttsx is a cross-platform speech (Mac OSX, Windows, and Linux) library. You can set voice metadata such as age, gender, id, language and name. Thee speech engine comes with a large amount of voices.

Text to speech sample:
 

Install with:


sudo pip install pyttsx

Create the code speech1.py


import pyttsx
engine = pyttsx.init()
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()

And execute it with python.

Espeak


eSpeak is a compact open source software speech synthesizer for English and other languages, for Linux and Windows.

Text to speech sample:
 

We can install using:


sudo apt-get install espeak

Create the code speech2.py:


import os
os.system("espeak 'The quick brown fox'")

It is very easy to use, but like pyttsx it sounds very robotic.

gTTS


The gtts module no longer works.

I found a script on Github that uses the Google speech engine. The script comes with many options and does not speak, instead it saves to an mp3. We added a command to play the mp3 automatically:


os.system("mpg321 out.mp3 -quiet")

Run with:


python gtts.py -s 'Python programming example'

The voice is extremely natural. The only disadvantage is that you need to be connected with the Internet when running this script.

Links


You might like:

String methods

Methods can be applied to Python strings, where a string is somet text between quotes. An example of using the string method replace, which replaces the a sub-string in a string:


s = "Hello World"
s = s.replace("World","Python")
print(s)

Related Course:
Python Programming Bootcamp: Go from zero to hero

Overview
Python includes these useful methods for string manipulation:



Method with description
capitalize(str)
Returns first letter capitalized string.
count(str)
Count the frequency of the word str. It can also be applied to words: s.count("Hello")
find(str)
Find the position of the first occurence.
index(str)
Find the position of the first occurence, raise exception if not found.
isdecimal()
Returns true if string is decimal.
isdigit()
Returns true if string contains digits only.
isnumeric()
Returns true if string contains numeric only.
lower()
Returns string in lowercase.
len(str)
Returns the length of str.
upper()
Returns string in uppercase.
replace(old, new)
Replaces the first argument with the second argument.

Métodos de cadena

Un ejemplo de uso de un método de cadena:


s = "Hola mundo"
s = s.replace("World","Python")
Print(s)

Descripción general
Python incluye estos métodos útiles para la manipulación de la cadena:



Método Descripción
capitalize(STR)
Regresa primera letra mayúscula string.
count(STR)
Contar la frecuencia de la palabra str. También se puede aplicar a las palabras: s.count("Hello")
Find(STR)
Encontrar la posición de la primera aparición.
index(STR)
Encontrar la posición de la primera aparición, excepción si no se encuentra.
isdecimal()
Devuelve true si la cadena es decimal.
isdigit()
Devuelve true si la cadena contiene sólo dígitos.
IsNumeric()
Devuelve true si la cadena contiene sólo numérico.
Lower()
Devuelve la cadena en minúsculas.
len(STR)
Devuelve la longitud de str.
Upper()
Devuelve la cadena en mayúsculas.
reemplazar (antiguo, nuevo)
Sustituye el primer argumento por el segundo argumento.

Math operations

Python has support for both mathematical operations and functions.

Mathematical operations
An overview of operations:



Operation Result
x + y sum of x and y.
x * y multiplication of x and y.
x - y difference of x and y.
x / y division of x by y.
x % y remainder of x/y
x ** y x to the power of y
abs(x) absolute value of x
sqrt(x) square root of x

Mathematical functions
Python supports a wide variety of mathematical functions.



Function Returns Example
abs(x) Returns the absolute value of x. {% codeblock lang:python line_number:false %} x = -35 x = abs(x) print(x) {% endcodeblock %}
cmp(x,y) Returns -1 if x < y
Returns 0 if x equals to y
Returns 1 if x > y.
{% codeblock lang:python line_number:false %} x = 6 y = 4 print( cmp(x,y) ) {% endcodeblock %}
exp(x) Returns the exponential of x {% codeblock lang:python line_number:false %} import math x = 6 print( math.exp(x) ) {% endcodeblock %}
log(x) The natural logarithm of x {% codeblock lang:python line_number:false %} import math x = 6 print( math.log(x) ) {% endcodeblock %}
log10(x) The base-10 logarithm of x {% codeblock lang:python line_number:false %} import math x = 6 print( math.log10(x) ) {% endcodeblock %}
pow(x,y) The result of x**y {% codeblock lang:python line_number:false %} import math x = 6 print( math.pow(x,2) ) {% endcodeblock %}
sqrt(x) The square root of x {% codeblock lang:python line_number:false %} import math x = 6 print( math.sqrt(x) ) {% endcodeblock %}

Tip
You can use the Python interpreter as calculator. To do so you simply start Python without an IDE and filename. Example:


Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type “help”, “copyright”, “credits” or “license” for more information.
>>> 18*17
306
>>> 2**4
16
>>>


Overview of Python IDEs and Code Editors

Install a Python IDE


An Integrated Desktop Environment (IDE) is a software application for programming. In addition to simple text editing they have all kind of features such as syntax highlighting, code completion, tabs, a class browser and many more.


Online Python Interpreters


The online interpreters may not work for everything but will work for most of the beginner tutorials. I recommend using a desktop IDE or the official Python interpreter.


Overview of IDEs (You only need one)


IDE Author Platform Description Price Download
PyCharm Jetbrains Windows, Mac OS X, Linux/UNIX Python IDE. Features including: code completion, code inspections, on-the-fly error highlighting and quick-fixes € 89 / 1st year.($ 97.90) Download PyCharm 
Atom (+script plugin) GitHub Windows, Mac OS X, Linux/UNIX Python IDE. You need to download the script plugin after installing Atom. Free. Download Atom.
Pythonista omz:software Apple iOS (iPhone, iPad) Features include: Syntax highlighting, code completion, interactive prompt, standard and iOS modules. € 9. ($ 9.90) Download Pythonista.
Eclipse with PyDev Aleks Totic Windows, Mac OS X, Linux/UNIX Features include: Syntax highlighting, code refactoring, graphical debugging and more. Free Download 
Eric Python IDE Detlev Offenbach Windows, Linux/UNIX Features include: Syntax highlighting, autocompletion, class browser and more. Free Download 
Wing IDE Wingware Windows, Mac OS X, Linux/UNIX Features: Syntax highlighting, auto completion, refactoring, unit testing and version control. $45 to $245 per user / license. Download 
Komodo IDE Komodo Windows, Mac OS X, Linux/UNIX Features: Syntax highlighting, documentation browser, run code in-line, quick bookmarks and more. € 40 to € 223. ($99 to $295). Download
Repl.it Amjad Masad, Haya Odeh, Faris Masad and Max Shawabkeh. Web Python interpreter Free Run Online 
Ideone Ideone Web Python interpreter Free Run Online 
Codepad Steven Hazel Web Python interpreter Free Run Online 

Función

Una función es un código reutilizable.
Nosotros usamos ese código.


def function(parameters):
instructions
return value

Ejemplo


Un ejemplo de una función:


#!/usr/bin/python

def f(x):
return x*x

print(f(3))

Resultado:

9

Esa función tiene un parámetro, x. El valor de retorno no es siempre necesario.

Función con mas parámetros.


Es posible usar mas parámetros.
Es posible usar variables en el código bloque:


#!/usr/bin/python

def f(x,y):
print 'You called f(x,y) with the value x = ' + str(x) + ' and y = ' + str(y)
print 'x * y = ' + str(x*y)

print(f(3,2))

Resultado:

You called f(x,y) with the value x = 3 and y = 2
x * y = 6

Función en una función


Es posible usar una función en una función.


#!/usr/bin/python

def highFive():
return 5

def f(x,y):
z = highFive() # we get the variable contents from highFive()
return x+y+z # returns x+y+z. z is reachable becaue it is defined above

result = f(3,2)
print(result)

Loops

Es posible repetir una parte del codigo con un bucle/loop.
Un loop repite instrucciones en un codigo de bloqueo

Ejemplo de Python para circuito (loop):
Nosotros podemos repetir una lista con un “for-loop”


#!/usr/bin/python

items = [ "Abby","Brenda","Cindy","Diddy" ]

for item in items:
print(item)

Abby
Brenda
Cindy
Diddy

Tambien es posible repetir/contar con circuitos


#!/usr/bin/python

for i in range(1,10):
print(i)

1
2
..
8
9

While-loop
Un bucle completo, repite un codigo bloque hasta que una condicion sea verdadera


while engine_on:
drive()

Random

Con el modulo random es posible generar valor aleatorio.
La funcion aleatoria ( ) genera valores entre cero y uno.

Valor aleatorio entre cero y uno.
Nosotors puedemos generar una valor aleatorio entre cero y uno con ese código:


from random import *

print random() # Generate a pseudo-random number between 0 and 1.

Valor aleatorio entre 1 y 100
Para generar un valor entre 1 y 100 use este código:


from random import *

x = randint(1, 100) # Pick a random number between 1 and 100.
print(x)

Valor aleatorio entre 1 y 10
Para generar un valor entre 1 y 10 use este código:


from random import *

print uniform(1, 10)

integers:


from random import *

x = randint(1, 100) # Pick a random number between 1 and 100.
print(x)

Jugar con la lista
Barajar una lista con ese código:


from random import *

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
shuffle(items)
print items

Escoger un valor con:


from random import *

items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

x = sample(items, 1) # Pick a random item from the list
print(x[0])

y = sample(items, 4) # Pick 4 random items from the list
print(y)

Igualmente con la cadena de caracteres:


from random import *

items = ['Alissa','Alice','Marco','Melissa','Sandra','Steve']

x = sample(items, 1) # Pick a random item from the list
print(x[0])

y = sample(items, 4) # Pick 4 random items from the list
print(y)

Personal Assistant (Jarvis) in Python

I thought it would be cool to create a personal assistant in Python. If you are into movies you may have heard of Jarvis, an A.I. based character in the Iron Man films. In this tutorial we will create a robot.

The features I want to have are:

For this tutorial you will need (Ubuntu) Linux, Python and a working microphone.

Related course:

Video


This is what you’ll create (watch the whole video, demo at the end):

Recognize spoken voice


Speech recognition can by done using the Python SpeechRecognition module. We make use of the Google Speech API because of it’s great quality.

Answer in spoken voice (Text To Speech)


Various APIs and programs are available for text to speech applications. Espeak and pyttsx work out of the box but sound very robotic. We decided to go with the Google Text To Speech API, gTTS.


sudo pip install gTTS

Using it is as simple as:


from gtts import gTTS
import os
tts = gTTS(text='Hello World', lang='en')
tts.save("hello.mp3")
os.system("mpg321 hello.mp3")

gtts

Complete program


The program below will answer spoken questions.


#!/usr/bin/env python3
# Requires PyAudio and PySpeech.

import speech_recognition as sr
from time import ctime
import time
import os
from gtts import gTTS

def speak(audioString):
print(audioString)
tts = gTTS(text=audioString, lang='en')
tts.save("audio.mp3")
os.system("mpg321 audio.mp3")

def recordAudio():
# Record Audio
r = sr.Recognizer()
with sr.Microphone() as source:
print("Say something!")
audio = r.listen(source)

# Speech recognition using Google Speech Recognition
data = ""
try:
# Uses the default API key
# To use another API key: `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
data = r.recognize_google(audio)
print("You said: " + data)
except sr.UnknownValueError:
print("Google Speech Recognition could not understand audio")
except sr.RequestError as e:
print("Could not request results from Google Speech Recognition service; {0}".format(e))

return data

def jarvis(data):
if "how are you" in data:
speak("I am fine")

if "what time is it" in data:
speak(ctime())

if "where is" in data:
data = data.split(" ")
location = data[2]
speak("Hold on Frank, I will show you where " + location + " is.")
os.system("chromium-browser https://www.google.nl/maps/place/" + location + "/&amp;")

# initialization
time.sleep(2)
speak("Hi Frank, what can I do for you?")
while 1:
data = recordAudio()
jarvis(data)


Related posts:


 

Introduction to GUI

To create a graphical interface (GUI) in Python you need to make use of a library or module.  There are at least three widely used modules for creating GUIs with Python:

While you can create a graphical user interface (GUI) with any of these modules, they do not have the same features.

Related course:

GUI toolkits


Tk provides basic widgets such as a button, menu, text and label. It is very limited compared to QT4 and WxPython but it is also the oldest module.  It runs on most versions of Mac OS, Linux and Windows.

TkMessage box a messagebox in Tk. GUIs made in Tk do not have a native look.

QT4 and QT5 are developed by the Qt company.  Graphical applications made with QT4 or QT5 run on Windows, Linux/X11 and Mac OS X.  It has tons of widgets including tabs, buttons, item views, table views, progressbars, input fields, calendar views and many more. Compared to Tk it has a lot more widgets available.

Graphical application using PyQt5

WxPython is a module that creates a native GUI look regardless of the operating system used. On Windows it will look as windows application while on Mac OS it will look as a Mac application. This can be a clear advantage compared to QT4 or Tk, depending on your purpose. WxWidgets has many widgets available such as buttons, menu, text but also more advanced widgets as a htmlview or tree control.

wxTabs A window created with wxPython. wxPython has native appearance on all operating systems.