<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Python</title>
	<atom:link href="/python/feed/" rel="self" type="application/rss+xml" />
	<link>https://talkera.org/python</link>
	<description>Programming Blog</description>
	<lastBuildDate>Sun, 01 Feb 2015 17:15:10 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=4.1</generator>
	<item>
		<title>Python Database Programming: SQLite (tutorial)</title>
		<link>https://talkera.org/python/python-database-programming-sqlite-tutorial/</link>
		<comments>https://talkera.org/python/python-database-programming-sqlite-tutorial/#comments</comments>
		<pubDate>Sun, 01 Feb 2015 17:15:10 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[Database]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[database]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[RDBMS]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=123</guid>
		<description><![CDATA[In this tutorial you will learn how to use the SQLite database management system with Python.  You will learn how to use SQLite, SQL queries, RDBMS and more of this cool stuff! Data is everywhere and software applications use that. Data is either in memory, files or databases. One of these database management systems (DBMS) [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In this tutorial you will learn how to use the SQLite database management system with Python.  You will learn how to use SQLite, SQL queries, RDBMS and more of this cool stuff!</p>
<p>Data is everywhere and software applications use that. Data is either in memory, files or databases. One of these database management systems (DBMS) is called SQLite.  SQLite was created in the year 2000 for a missile control system (boom! did we say it was cool?) and is one of the many management systems in the database zoo. MySQL, Postregsql, Oracle, Microsoft SQL Server and Maria DB are other database animals in this zoo.  So what is this <em>SQL</em>?</p>
<p>SQL is a special-purpose programming language designed for managing data held in a databases. The language has been around since 1986 and is worth learning. The video below is an old funny video about SQL.</p>
<p><iframe width="580" height="435" src="https://www.youtube.com/embed/5ycx9hFGHog?feature=oembed" frameborder="0" allowfullscreen></iframe></p>
<p>Why use SQLite? SQLite is the most widely deployed SQL database engine in the world. The source code for SQLite is in the public domain. It is a self-contained, serverless, zero-configuration, transactional SQL database engine. The SQLite project is sponsored by Bloomberg and Mozilla.</p>
<p><strong>Installation:</strong></p><pre class="crayon-plain-tag">$ sudo apt-get install sqlite</pre><p>Verify if it is correctly installed. Copy this program and save it as test1.py</p><pre class="crayon-plain-tag">#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = None

try:
    con = lite.connect('test.db')
    cur = con.cursor()    
    cur.execute('SELECT SQLITE_VERSION()')
    data = cur.fetchone()
    print "SQLite version: %s" % data                
except lite.Error, e:   
    print "Error %s:" % e.args[0]
    sys.exit(1)
finally:    
    if con:
        con.close()</pre><p>Execute with:</p><pre class="crayon-plain-tag">$ python test1.py</pre><p>It should output:</p><pre class="crayon-plain-tag">SQLite version: 3.8.2</pre><p><strong>What did the script above do?</strong><br />
The script connected to a new database called test.db with this line:</p><pre class="crayon-plain-tag">con = lite.connect('test.db')</pre><p>It then queries the database management system with the command</p><pre class="crayon-plain-tag">SELECT SQLITE_VERSION()</pre><p>which in turn returned its version number. That line is known as an SQL query.</p>
<div id="attachment_139" style="width: 607px" class="wp-caption alignnone"><a href="/python/wp-content/uploads/2015/02/db.png"><img class="wp-image-139 size-full" src="/python/wp-content/uploads/2015/02/db.png" alt="SQL joke. From Reddit" width="597" height="181" /></a><p class="wp-caption-text">SQL joke. Source: Reddit</p></div>
<p><strong>Storing data</strong><br />
The script below will store data into a new database called user.db</p><pre class="crayon-plain-tag">#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('user.db')

with con:
    
    cur = con.cursor()    
    cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
    cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
    cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
    cur.execute("INSERT INTO Users VALUES(3,'Greg')")</pre><p>SQLite is a database management system that uses tables. These tables can have relations with other tables: it&#8217;s called relational database management system or RDBMS.  The table defines the structure of the data and can hold the data.  A database can hold many different tables. The table gets created using the command:</p><pre class="crayon-plain-tag">cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")</pre><p>We add  records into the table with these commands:</p><pre class="crayon-plain-tag">cur.execute("INSERT INTO Users VALUES(2,'Sonya')")
    cur.execute("INSERT INTO Users VALUES(3,'Greg')")</pre><p>The first value is the ID. The second value is the name.  Once we run the script the data gets inserted into the database table Users:</p>
<p><a href="/python/wp-content/uploads/2015/02/table21.png"><img class="alignnone wp-image-153 size-full" src="/python/wp-content/uploads/2015/02/table21.png" alt="table2" width="335" height="106" /></a></p>
<p><strong>Exploring the data</strong><br />
We can explore the database using two methods:  the command line and a graphical interface.</p>
<p><em>From console:</em> To explore using the command line type these commands:</p><pre class="crayon-plain-tag">sqlite3 user.db
.tables
SELECT * FROM Users;</pre><p>This will output the data in the table Users.</p><pre class="crayon-plain-tag">sqlite&gt; SELECT * FROM Users;
1|Michelle
2|Sonya
3|Greg</pre><p><em>From GUI:</em> If you want to use a GUI instead, there is a lot of choice. Personally I picked sqllite-man but there are <a href="https://stackoverflow.com/questions/835069/which-sqlite-administration-console-do-you-recommend" target="_blank">many others</a>. We install using:</p><pre class="crayon-plain-tag">sudo apt-get install sqliteman</pre><p>We start the application sqliteman. A gui pops up.</p>
<p><a href="/python/wp-content/uploads/2015/02/sqliteman.png"><img class="alignnone wp-image-134 size-full" src="/python/wp-content/uploads/2015/02/sqliteman.png" alt="sqliteman" width="668" height="661" /></a></p>
<p>Press File &gt; Open &gt; user.db.  It appears like not much has changed, do not worry, this is just the user interface.  On the left is a small tree view, press Tables &gt; users. The full table including all records will be showing now.</p>
<p><a href="/python/wp-content/uploads/2015/02/sqliteman2.png"><img class="alignnone wp-image-135 size-full" src="/python/wp-content/uploads/2015/02/sqliteman2.png" alt="sqliteman2" width="668" height="661" /></a></p>
<p>This GUI can be used to modify the records (data) in the table and to add new tables.</p>
<p><strong> The SQL language</strong><br />
SQL has many commands to interact with the database. You can try the commands below from the command line or from the GUI:</p><pre class="crayon-plain-tag">sqlite3 user.db 
SELECT * FROM Users;
SELECT count(*) FROM Users;
SELECT name FROM Users;
SELECT * FROM Users WHERE id = 2;
DELETE FROM Users WHERE id = 6;</pre><p>We can use those queries in a Python program:</p><pre class="crayon-plain-tag">#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys


con = lite.connect('user.db')

with con:    
    
    cur = con.cursor()    
    cur.execute("SELECT * FROM Users")

    rows = cur.fetchall()

    for row in rows:
        print row</pre><p>This will output all data in the Users table from the database:</p><pre class="crayon-plain-tag">$ python get.py 
(1, u'Michelle')
(2, u'Sonya')
(3, u'Greg')</pre><p>&nbsp;</p>
<div id="attachment_174" style="width: 650px" class="wp-caption alignnone"><a href="/python/wp-content/uploads/2015/02/joke.jpg"><img class="wp-image-174 size-full" src="/python/wp-content/uploads/2015/02/joke.jpg" alt="SQL joke. Source: flickr" width="640" height="426" /></a><p class="wp-caption-text">SQL joke. Source: flickr</p></div>
<p><strong>Creating a user information database</strong><br />
We can structure our data across multiple tables. This keeps our data structured, fast and organized.  If we would have a single table to store everything, we would quickly have a big chaotic mess. What we will do is create multiple tables and use them in a combination. We create two tables:</p>
<p><em>Users:</em></p>
<p><a href="/python/wp-content/uploads/2015/02/t1.png"><img class="alignnone wp-image-165 size-full" src="/python/wp-content/uploads/2015/02/t1.png" alt="t1" width="514" height="102" /></a></p>
<p><em>Jobs:</em></p>
<p><a href="/python/wp-content/uploads/2015/02/t2.png"><img class="alignnone wp-image-166 size-full" src="/python/wp-content/uploads/2015/02/t2.png" alt="t2" width="514" height="100" /></a></p>
<p>To create these tables, you can do that by hand in the GUI or use the script below:</p><pre class="crayon-plain-tag"># -*- coding: utf-8 -*-
 
import sqlite3 as lite
import sys
 
con = lite.connect('system.db')
 
with con:
    
    cur = con.cursor()    
    cur.execute("CREATE TABLE Users(Id INT, Name TEXT)")
    cur.execute("INSERT INTO Users VALUES(1,'Michelle')")
    cur.execute("INSERT INTO Users VALUES(2,'Howard')")
    cur.execute("INSERT INTO Users VALUES(3,'Greg')")

    cur.execute("CREATE TABLE Jobs(Id INT, Uid INT, Profession TEXT)")
    cur.execute("INSERT INTO Jobs VALUES(1,1,'Scientist')")
    cur.execute("INSERT INTO Jobs VALUES(2,2,'Marketeer')")
    cur.execute("INSERT INTO Jobs VALUES(3,3,'Developer')")</pre><p>The jobs table has an extra parameter, Uid. We use that to connect the two tables in an SQL query:</p><pre class="crayon-plain-tag">SELECT users.name, jobs.profession FROM jobs INNER JOIN users ON users.ID = jobs.uid</pre><p>You can incorporate that SQL query in a Python script:</p><pre class="crayon-plain-tag">#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys


con = lite.connect('system.db')

with con:    
    
    cur = con.cursor()    
    cur.execute("SELECT users.name, jobs.profession FROM jobs INNER JOIN users ON users.ID = jobs.uid")

    rows = cur.fetchall()

    for row in rows:
        print row</pre><p>It should output:</p><pre class="crayon-plain-tag">$ python get2.py
(u'Michelle', u'Scientist')
(u'Howard', u'Marketeer')
(u'Greg', u'Developer')</pre><p>If you liked this tutorial please share it using one of the buttons below <img src="/python/wp-includes/images/smilies/icon_smile.gif" alt=":)" class="wp-smiley" /></p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;linkname=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fpython-database-programming-sqlite-tutorial%2F&amp;title=Python%20Database%20Programming%3A%20SQLite%20%28tutorial%29" id="wpa2a_2"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/python-database-programming-sqlite-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a webbrowser with Python and PyQT (tutorial)</title>
		<link>https://talkera.org/python/creating-a-webbrowser-with-python-and-pyqt-tutorial/</link>
		<comments>https://talkera.org/python/creating-a-webbrowser-with-python-and-pyqt-tutorial/#comments</comments>
		<pubDate>Fri, 30 Jan 2015 20:40:16 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[pyqt]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[qt]]></category>
		<category><![CDATA[webbrowser]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=115</guid>
		<description><![CDATA[In this tutorial we will build a webbrowser with Python. We will use PyQT.  Install the required packages: [crayon-54ceeeb965637132541761/] If you have not done our first tutorial, you could try it. If python-kde4 cannot be found update your repository to find it. If you are on Ubuntu or Debian Linux use this link. Creating the [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In this tutorial we will build a webbrowser with Python. We will use PyQT.  Install the required packages:</p><pre class="crayon-plain-tag">sudo pip install python-qt4
sudo apt-get install qt4-designer
sudo apt-get install pyqt4-dev-tools
sudo apt-get install python-kde4</pre><p>If you have not done our <a href="/python/building-an-application-gui-with-pyqt-beginners-tutorial/" target="_blank">first tutorial</a>, you could try it. If python-kde4 cannot be found update your repository to find it. If you are on Ubuntu or Debian Linux use <a href="http://packages.ubuntu.com/precise/i386/python-kde4/download" target="_blank">this link</a>.</p>
<p><strong>Creating the UI with PyQT</strong><br />
Start qt4-designer from your applications menu. The QT Designer application will appear:</p>
<div id="attachment_77" style="width: 590px" class="wp-caption alignnone"><a href="/python/wp-content/uploads/2015/01/QT_Designer.jpg"><img class="wp-image-77 size-large" src="/python/wp-content/uploads/2015/01/QT_Designer-1024x557.jpg" alt="QT_Designer" width="580" height="315" /></a><p class="wp-caption-text">QT_Designer</p></div>
<p>Select Main Window and press Create. We now have our designer window open.  Drag a<em> KWebView</em> component on the window. If you have a<em> QtWebView</em> in the component list. use that instead. We also add an<em> Line Edit</em> on top. Press File &gt; Save As &gt; browser.ui.  Run the command:</p><pre class="crayon-plain-tag">pyuic4 browser.ui &gt; browser.py</pre><p>This will generate a Python file. Remove the line &#8220;from kwebview import KWebView&#8221; from the bottom of the browser.py file. Change KWebView to QtWebView. We want to use QtWebView instead. If you are lazy to change that, take the browser.py file from below.</p>
<p><strong>Creating the logic.</strong><br />
Create a file called<strong><em> r</em></strong><em><strong>un.py</strong></em> with this contents:</p><pre class="crayon-plain-tag">import sys
from browser import BrowserDialog
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView

class MyBrowser(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        QWebView.__init__(self)
        self.ui = BrowserDialog()
        self.ui.setupUi(self)
        self.ui.lineEdit.returnPressed.connect(self.loadURL)
 
    def loadURL(self):
        url = self.ui.lineEdit.text()
        self.ui.qwebview.load(QUrl(url))
        self.show()  
        #self.ui.lineEdit.setText("")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyBrowser()
    myapp.ui.qwebview.load(QUrl('https://talkera.org/python'))
    myapp.show()
    sys.exit(app.exec_())</pre><p>This code will use the UI as defined in browser.py and add logic to it. The lines</p><pre class="crayon-plain-tag">self.ui.lineEdit.returnPressed.connect(self.loadURL)
 
    def loadURL(self):
        url = self.ui.lineEdit.text()
        self.ui.qwebview.load(QUrl(url))
        self.show()  
        #self.ui.lineEdit.setText("")</pre><p>The first line defines the callback or event. If a person presses enter (returnPressed), it will call the function loadURL. It makes sure that once you press enter, the page is loaded with that function. If you did everything correctly, you should be able to run the browser with the command:</p><pre class="crayon-plain-tag">python run.py</pre><p>Please make sure you type the full url, e.g.  : https://talkera.org including the http:// part.  Your browser should now start:</p>
<p><a href="/python/wp-content/uploads/2015/01/browser.png"><img class="alignnone wp-image-119 size-large" src="/python/wp-content/uploads/2015/01/browser-1024x742.png" alt="browser" width="580" height="420" /></a></p>
<p>If your code does not run, please use the codes below (or look at the differences and change whats wrong):</p>
<p><strong>browser.py</strong></p><pre class="crayon-plain-tag"># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'browser.ui'
#
# Created: Fri Jan 30 20:49:32 2015
#      by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!

import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtGui import QApplication
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class BrowserDialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(1024, 768)
        self.qwebview = QWebView(Dialog)
        self.qwebview.setGeometry(QtCore.QRect(0, 50, 1020, 711))
        self.qwebview.setObjectName(_fromUtf8("kwebview"))
        self.lineEdit = QtGui.QLineEdit(Dialog)
        self.lineEdit.setGeometry(QtCore.QRect(10, 20, 1000, 25))
        self.lineEdit.setObjectName(_fromUtf8("lineEdit"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Browser", "Browser", None))</pre><p><strong>run.py</strong></p><pre class="crayon-plain-tag">import sys
from browser import BrowserDialog
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import QUrl
from PyQt4.QtWebKit import QWebView

class MyBrowser(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        QWebView.__init__(self)
        self.ui = BrowserDialog()
        self.ui.setupUi(self)
        self.ui.lineEdit.returnPressed.connect(self.loadURL)
 
    def loadURL(self):
        url = self.ui.lineEdit.text()
        self.ui.qwebview.load(QUrl(url))
        self.show()  
        #self.ui.lineEdit.setText("")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyBrowser()
    myapp.ui.qwebview.load(QUrl('https://talkera.org/python'))
    myapp.show()
    sys.exit(app.exec_())</pre><p></p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-webbrowser-with-python-and-pyqt-tutorial%2F&amp;linkname=Creating%20a%20webbrowser%20with%20Python%20and%20PyQT%20%28tutorial%29" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-webbrowser-with-python-and-pyqt-tutorial%2F&amp;linkname=Creating%20a%20webbrowser%20with%20Python%20and%20PyQT%20%28tutorial%29" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-webbrowser-with-python-and-pyqt-tutorial%2F&amp;linkname=Creating%20a%20webbrowser%20with%20Python%20and%20PyQT%20%28tutorial%29" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-webbrowser-with-python-and-pyqt-tutorial%2F&amp;linkname=Creating%20a%20webbrowser%20with%20Python%20and%20PyQT%20%28tutorial%29" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-webbrowser-with-python-and-pyqt-tutorial%2F&amp;linkname=Creating%20a%20webbrowser%20with%20Python%20and%20PyQT%20%28tutorial%29" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-webbrowser-with-python-and-pyqt-tutorial%2F&amp;linkname=Creating%20a%20webbrowser%20with%20Python%20and%20PyQT%20%28tutorial%29" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-webbrowser-with-python-and-pyqt-tutorial%2F&amp;title=Creating%20a%20webbrowser%20with%20Python%20and%20PyQT%20%28tutorial%29" id="wpa2a_4"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/creating-a-webbrowser-with-python-and-pyqt-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Speech engines with Python (tutorial)</title>
		<link>https://talkera.org/python/speech-engines-with-python-tutorial/</link>
		<comments>https://talkera.org/python/speech-engines-with-python-tutorial/#comments</comments>
		<pubDate>Wed, 28 Jan 2015 14:08:58 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[Audio]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[sound]]></category>
		<category><![CDATA[speech]]></category>
		<category><![CDATA[synthesis]]></category>
		<category><![CDATA[TTS]]></category>
		<category><![CDATA[voice]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=108</guid>
		<description><![CDATA[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? Pyttsx Pyttsx is a cross-platform speech (Mac OSX, Windows, and Linux) library. You can set [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>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?</p>
<p><strong>Pyttsx</strong><br />
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. Sadly, the default voice sounds very robotic.</p><pre class="crayon-plain-tag">sudo pip install pyttsx</pre><p>Create the code speech1.py</p><pre class="crayon-plain-tag">import pyttsx
engine = pyttsx.init()
engine.say('The quick brown fox jumped over the lazy dog.')
engine.runAndWait()</pre><p>And execute it with python.</p>
<p><strong>Espeak</strong><br />
eSpeak is a compact open source software speech synthesizer for English and other languages, for Linux and Windows.  We can install using:</p><pre class="crayon-plain-tag">sudo apt-get install espeak</pre><p>Create the code speech2.py:</p><pre class="crayon-plain-tag">import os
os.system("espeak 'The quick brown fox'")</pre><p>It is very easy to use, but like pyttsx it sounds very robotic.</p>
<p><strong>GoogleTTS</strong><br />
I found <a href="https://raw.githubusercontent.com/hungtruong/Google-Translate-TTS/master/GoogleTTS.py" target="_blank">a script</a> 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:</p><pre class="crayon-plain-tag">os.system("mpg321 out.mp3 -quiet")</pre><p>Run with:</p><pre class="crayon-plain-tag">python gtts.py -s 'Python programming example'</pre><p>The voice is extremely natural. The only disadvantage is that you need to be connected with the Internet when running this script.</p>
<p><strong> Conclusion</strong><br />
GoogleTTS is the most natural speech synthesis engine that we found. While other TTS engines are simple to use they simply do not match the sound quality.  Sadly the number of available voices is limited.</p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fspeech-engines-with-python-tutorial%2F&amp;linkname=Speech%20engines%20with%20Python%20%28tutorial%29" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fspeech-engines-with-python-tutorial%2F&amp;linkname=Speech%20engines%20with%20Python%20%28tutorial%29" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fspeech-engines-with-python-tutorial%2F&amp;linkname=Speech%20engines%20with%20Python%20%28tutorial%29" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fspeech-engines-with-python-tutorial%2F&amp;linkname=Speech%20engines%20with%20Python%20%28tutorial%29" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fspeech-engines-with-python-tutorial%2F&amp;linkname=Speech%20engines%20with%20Python%20%28tutorial%29" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fspeech-engines-with-python-tutorial%2F&amp;linkname=Speech%20engines%20with%20Python%20%28tutorial%29" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fspeech-engines-with-python-tutorial%2F&amp;title=Speech%20engines%20with%20Python%20%28tutorial%29" id="wpa2a_6"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/speech-engines-with-python-tutorial/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>QML and PyQT: Creating a GUI (tutorial)</title>
		<link>https://talkera.org/python/qml-and-pyqt-creating-a-gui-tutorial/</link>
		<comments>https://talkera.org/python/qml-and-pyqt-creating-a-gui-tutorial/#comments</comments>
		<pubDate>Tue, 27 Jan 2015 19:10:24 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[pyqt]]></category>
		<category><![CDATA[QML]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=90</guid>
		<description><![CDATA[If you have not done our first PyQT tutorial yet, you should do it, it&#8217;s fun! In this tutorial we will use an user interface markup language, a language that describes the graphical  user interfaces and controls .  An excerpt of user interface markup language code could look like: [crayon-54ceeeb9662e7651513812/] Essentially the language tells what [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>If you have not done our <a href="/python/building-an-application-gui-with-pyqt-beginners-tutorial/" target="_blank">first PyQT tutorial</a> yet, you should do it, it&#8217;s fun! In this tutorial we will use an user interface markup language, a language that <em>describes the graphical  user interfaces and controls</em> .  An excerpt of user interface markup language code could look like:</p><pre class="crayon-plain-tag">Rectangle {
     id: simplebutton
     color: "grey"
     width: 150; height: 75</pre><p>Essentially the language tells what the interface should look like. The language we will be using is called QML. Do not worry about it for now.</p>
<p>Start a programmed called QTCreator.   The tutorial will be quite graphical to help you through the whole process. Simply type <em>qtcreator</em> in the terminal or start it from the menu list.  This screen should pop up:</p>
<p><a href="/python/wp-content/uploads/2015/01/qtcreator.png"><img class="alignnone wp-image-91 size-full" src="/python/wp-content/uploads/2015/01/qtcreator.png" alt="qtcreator" width="1366" height="743" /></a></p>
<p>Press the big <strong><em>New Project</em> </strong>button. Select<em><strong> QT Quick Application</strong></em> from the menu below. Finally press<em><strong> Choose</strong></em> on the bottom right.</p>
<p><a href="/python/wp-content/uploads/2015/01/qtquick.png"><img class="alignnone wp-image-93 size-full" src="/python/wp-content/uploads/2015/01/qtquick.png" alt="QT Quick Project QML" width="882" height="545" /></a></p>
<p>A new popup will appear:</p>
<p><a href="/python/wp-content/uploads/2015/01/kde-create.png"><img class="alignnone wp-image-95 size-full" src="/python/wp-content/uploads/2015/01/kde-create.png" alt="kde create" width="902" height="475" /></a></p>
<p>Type a name and a valid path to save your project. Then press Next.  Select <em><strong>QT Quick 2.0</strong></em> from the menu list. Press Next. Press Finish. Immediately a user interface defined in the QML language will appear.</p>
<p><a href="/python/wp-content/uploads/2015/01/qtquick2.png"><img class="alignnone size-full wp-image-99" src="/python/wp-content/uploads/2015/01/qtquick2.png" alt="qtquick2" width="711" height="402" /></a></p>
<p>Like all great programmers we are going to solve things the most lazy way possible.  Instead of typing all the QML code by hand we are going to press the <em><strong>Design</strong> </em>button that is on the left of the screen.  A drag and drop screen should appear now.</p>
<p><a href="/python/wp-content/uploads/2015/01/draganddrop.png"><img class="alignnone size-full wp-image-101" src="/python/wp-content/uploads/2015/01/draganddrop.png" alt="QT draganddrop" width="810" height="467" /></a></p>
<p>We drag an image onto the area and select the source on the right. Save the project. Open a terminal and locate the qml file you just created. Alternatively you could simply copy the code in the edit box and save it to a .qml file. Enter the command:</p><pre class="crayon-plain-tag">qmlviewer main.qml</pre><p>This will display the windows as defined in the qml file without any functionality. It is simply a viewer for the interface.  We then create some code to load this QML definition:</p><pre class="crayon-plain-tag">import sys

from PyQt4.QtCore import QDateTime, QObject, QUrl, pyqtSignal
from PyQt4.QtGui import QApplication
from PyQt4.QtDeclarative import QDeclarativeView

app = QApplication(sys.argv)

# Create the QML user interface.
view = QDeclarativeView()
view.setSource(QUrl('main.qml'))
view.setResizeMode(QDeclarativeView.SizeRootObjectToView)
view.setGeometry(100, 100, 400, 240)
view.show()

app.exec_()</pre><p>Finally we modify the first line main.qml to:</p><pre class="crayon-plain-tag">import Qt 4.7</pre><p>Simply because our QtQuick was missing. Running</p><pre class="crayon-plain-tag">python run.py</pre><p>Will now display our user interface as defined by QML:</p>
<p><a href="/python/wp-content/uploads/2015/01/QML_PyQT.png"><img class="alignnone size-full wp-image-103" src="/python/wp-content/uploads/2015/01/QML_PyQT.png" alt="QML_PyQT" width="533" height="367" /></a></p>
<p>All of the code is simply PyQT, so you could add code like in the previous tutorial. These are the two methods to create a graphical interface with PyQT.  This method may be more loosely coupled to the code compared to the method of creating a GUI with QT in the previous tutorial. Despite that both are valid methods.</p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fqml-and-pyqt-creating-a-gui-tutorial%2F&amp;linkname=QML%20and%20PyQT%3A%20Creating%20a%20GUI%20%28tutorial%29" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fqml-and-pyqt-creating-a-gui-tutorial%2F&amp;linkname=QML%20and%20PyQT%3A%20Creating%20a%20GUI%20%28tutorial%29" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fqml-and-pyqt-creating-a-gui-tutorial%2F&amp;linkname=QML%20and%20PyQT%3A%20Creating%20a%20GUI%20%28tutorial%29" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fqml-and-pyqt-creating-a-gui-tutorial%2F&amp;linkname=QML%20and%20PyQT%3A%20Creating%20a%20GUI%20%28tutorial%29" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fqml-and-pyqt-creating-a-gui-tutorial%2F&amp;linkname=QML%20and%20PyQT%3A%20Creating%20a%20GUI%20%28tutorial%29" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fqml-and-pyqt-creating-a-gui-tutorial%2F&amp;linkname=QML%20and%20PyQT%3A%20Creating%20a%20GUI%20%28tutorial%29" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fqml-and-pyqt-creating-a-gui-tutorial%2F&amp;title=QML%20and%20PyQT%3A%20Creating%20a%20GUI%20%28tutorial%29" id="wpa2a_8"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/qml-and-pyqt-creating-a-gui-tutorial/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Building an application GUI with PyQT, beginners tutorial</title>
		<link>https://talkera.org/python/building-an-application-gui-with-pyqt-beginners-tutorial/</link>
		<comments>https://talkera.org/python/building-an-application-gui-with-pyqt-beginners-tutorial/#comments</comments>
		<pubDate>Mon, 26 Jan 2015 00:29:04 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[gui]]></category>
		<category><![CDATA[kde]]></category>
		<category><![CDATA[pyqt]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[qt]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=76</guid>
		<description><![CDATA[In this tutorial we will teach you how to create a graphical application with PyQT.  You will need to install some packages: [crayon-54ceeeb966951550135915/] If python-kde4 cannot be found update your repository to find it. If you are on Ubuntu use this link. Now we can use the QT Designer application. It saves us from writing [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>In this tutorial we will teach you how to create a graphical application with PyQT.  You will need to install some packages:</p><pre class="crayon-plain-tag">sudo pip install pyqt
sudo apt-get install qt4-designer
sudo apt-get install pyqt4-dev-tools
sudo apt-get install python-kde4</pre><p>If python-kde4 cannot be found update your repository to find it. If you are on Ubuntu use<a href="http://packages.ubuntu.com/precise/i386/python-kde4/download" target="_blank"> this link</a>.</p>
<p>Now we can use the QT Designer application. It saves us from writing tons of layout code that you may be used to when writing HTML.  Start qt4-designer from your applications menu. The QT Designer application will appear:</p>
<div id="attachment_77" style="width: 1376px" class="wp-caption alignnone"><a href="/python/wp-content/uploads/2015/01/QT_Designer.jpg"><img class="wp-image-77 size-full" src="/python/wp-content/uploads/2015/01/QT_Designer.jpg" alt="QT_Designer" width="1366" height="743" /></a><p class="wp-caption-text">QT_Designer</p></div>
<p>Press <em>Dialog without Buttons</em> and press<em> Create</em>. You can now drag any component from the widget box to the form. Simple drag and drop. We added a button, label and a pixmap.  (I took a random image from the web for the pixmap)</p>
<p><a href="/python/wp-content/uploads/2015/01/QT_KDE_Dialog.jpg"><img class="alignnone wp-image-82 size-full" src="/python/wp-content/uploads/2015/01/QT_KDE_Dialog.jpg" alt="QT_KDE_Dialog" width="549" height="259" /></a></p>
<p>Our window looks like the image above. Press Form &gt; Viewcode. We will get a popup box with the form code in&#8230; C++! That is great, but we want the Python code.   Press <em><strong>File &gt; Save as &gt; form.ui</strong></em>.</p>
<p>The file test.ui contains your form described in XML format. (You can view it in a text editor) Open a console and type:</p><pre class="crayon-plain-tag">pyuic4 form.ui &gt; form.py</pre><p>Running the file does nothing. Create a new file called  gui.py</p>
<p>Paste the code below:</p><pre class="crayon-plain-tag">import sys
from PyQt4 import QtCore, QtGui
from form import Ui_Dialog


class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyDialog()
    myapp.show()
    sys.exit(app.exec_())</pre><p>Run with:</p><pre class="crayon-plain-tag">python gui.py</pre><p>This will open our graphical interface. Pressing on the OK button will simply close the application.</p>
<p><a href="/python/wp-content/uploads/2015/01/pyqt_window.jpg"><img class="alignnone size-medium wp-image-83" src="/python/wp-content/uploads/2015/01/pyqt_window-300x215.jpg" alt="PyQT window" width="300" height="215" /></a></p>
<p>We want to add some action when the OK button is pressed.  We add these three lines to the code:</p><pre class="crayon-plain-tag">self.ui.pushButton.clicked.connect(self.OK)

    def OK(self):
        print 'OK pressed.'</pre><p>Please make sure your button is named pushButton by inspecting the<em> form.py</em> file. Pressing the button will print &#8216;OK pressed&#8217; to the terminal.</p>
<p><a href="/python/wp-content/uploads/2015/01/pyqt_window2.jpg"><img class="alignnone size-medium wp-image-84" src="/python/wp-content/uploads/2015/01/pyqt_window2-300x163.jpg" alt="pyqt_window2" width="300" height="163" /></a></p>
<p>Total application below:</p>
<p><strong>gui.py</strong></p><pre class="crayon-plain-tag">import sys
from PyQt4 import QtCore, QtGui
from form import Ui_Dialog


class MyDialog(QtGui.QDialog):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_Dialog()
        self.ui.setupUi(self)
        self.ui.pushButton.clicked.connect(self.OK)

    def OK(self):
        print 'OK pressed.'


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyDialog()
    myapp.show()
    sys.exit(app.exec_())</pre><p><strong>form.py (generated):</strong></p><pre class="crayon-plain-tag"># -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'form.ui'
#
# Created: Mon Jan 26 01:18:19 2015
#      by: PyQt4 UI code generator 4.10.4
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s

try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)

class Ui_Dialog(object):
    def setupUi(self, Dialog):
        Dialog.setObjectName(_fromUtf8("Dialog"))
        Dialog.resize(325, 208)
        self.label = QtGui.QLabel(Dialog)
        self.label.setGeometry(QtCore.QRect(30, 100, 341, 61))
        self.label.setObjectName(_fromUtf8("label"))
        self.pushButton = QtGui.QPushButton(Dialog)
        self.pushButton.setGeometry(QtCore.QRect(10, 150, 301, 41))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        self.kpixmapregionselectorwidget = KPixmapRegionSelectorWidget(Dialog)
        self.kpixmapregionselectorwidget.setGeometry(QtCore.QRect(-30, -20, 371, 161))
        self.kpixmapregionselectorwidget.setPixmap(QtGui.QPixmap(_fromUtf8("Desktop/IMG_0377.jpg")))
        self.kpixmapregionselectorwidget.setObjectName(_fromUtf8("kpixmapregionselectorwidget"))

        self.retranslateUi(Dialog)
        QtCore.QMetaObject.connectSlotsByName(Dialog)

    def retranslateUi(self, Dialog):
        Dialog.setWindowTitle(_translate("Dialog", "Dialog", None))
        self.label.setText(_translate("Dialog", "This form is created with Python and QT.", None))
        self.pushButton.setText(_translate("Dialog", "OK", None))

from PyKDE4.kdeui import KPixmapRegionSelectorWidget</pre><p>&nbsp;</p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-application-gui-with-pyqt-beginners-tutorial%2F&amp;linkname=Building%20an%20application%20GUI%20with%20PyQT%2C%20beginners%20tutorial" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-application-gui-with-pyqt-beginners-tutorial%2F&amp;linkname=Building%20an%20application%20GUI%20with%20PyQT%2C%20beginners%20tutorial" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-application-gui-with-pyqt-beginners-tutorial%2F&amp;linkname=Building%20an%20application%20GUI%20with%20PyQT%2C%20beginners%20tutorial" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-application-gui-with-pyqt-beginners-tutorial%2F&amp;linkname=Building%20an%20application%20GUI%20with%20PyQT%2C%20beginners%20tutorial" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-application-gui-with-pyqt-beginners-tutorial%2F&amp;linkname=Building%20an%20application%20GUI%20with%20PyQT%2C%20beginners%20tutorial" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-application-gui-with-pyqt-beginners-tutorial%2F&amp;linkname=Building%20an%20application%20GUI%20with%20PyQT%2C%20beginners%20tutorial" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-application-gui-with-pyqt-beginners-tutorial%2F&amp;title=Building%20an%20application%20GUI%20with%20PyQT%2C%20beginners%20tutorial" id="wpa2a_10"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/building-an-application-gui-with-pyqt-beginners-tutorial/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Creating a gui in Python with WxWidgets [tutorial for beginners]</title>
		<link>https://talkera.org/python/creating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners/</link>
		<comments>https://talkera.org/python/creating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners/#comments</comments>
		<pubDate>Fri, 23 Jan 2015 22:19:10 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[GUI]]></category>
		<category><![CDATA[gui]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[wx]]></category>
		<category><![CDATA[wxpython]]></category>
		<category><![CDATA[wxwidgets]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=67</guid>
		<description><![CDATA[Python programming is a lot of fun and sometimes we want to create a graphical application (GUI). WxWidgets can be used to create a graphical interface that looks like a native application on any operating system. First download and install WxPython, the Python bindings for wxWidgets. [crayon-54ceeeb967242051551736/] Then install a GUI creator called wxglade: [crayon-54ceeeb96724d210156723/] [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Python programming is a lot of fun and sometimes we want to create a graphical application (GUI). WxWidgets can be used to create a graphical interface that looks like a native application on any operating system. First download and install WxPython, the Python bindings for wxWidgets.</p><pre class="crayon-plain-tag">sudo apt-get install python-wxgtk2.8 python-wxtools wx2.8-doc wx2.8-examples wx2.8-headers wx2.8-i18n</pre><p>Then install a GUI creator called wxglade:</p><pre class="crayon-plain-tag">sudo apt-get install wxglade</pre><p>Using a GUI builder such as wxGlade will save you a lot of time, regardless of the GUI library you use. You can easily make complex graphical interfaces because you can simply drag and drop.</p>
<p><strong>Creating our first GUI with Python and wxWidgets:</strong></p>
<p>Start wxglade. You will see its user interface:</p>
<p><a href="/python/wp-content/uploads/2015/01/wxglade.jpeg"><img class="alignnone size-full wp-image-68" src="/python/wp-content/uploads/2015/01/wxglade.jpeg" alt="wxglade" width="163" height="206" /></a></p>
<p>Press on tiny window on the top left, below the file icon.</p>
<p><a href="/python/wp-content/uploads/2015/01/wxglade2.png"><img class="alignnone size-full wp-image-69" src="/python/wp-content/uploads/2015/01/wxglade2.png" alt="wxglade frame" width="192" height="170" /></a></p>
<p>Press OK.  An empty window will now appear.  Press on the tiny [OK] button in the wxGlade panel and press on the frame. The button will now appear. Press on Application in the tree window.</p>
<p><a href="/python/wp-content/uploads/2015/01/wxglade2.jpg"><img class="alignnone size-medium wp-image-71" src="/python/wp-content/uploads/2015/01/wxglade2-300x300.jpg" alt="wxglade2" width="300" height="300" /></a></p>
<p>Set the output file in the wxproperties window.</p>
<p><a href="/python/wp-content/uploads/2015/01/wxglade3.jpg"><img class="alignnone size-medium wp-image-72" src="/python/wp-content/uploads/2015/01/wxglade3-214x300.jpg" alt="wxglade3" width="214" height="300" /></a></p>
<p>If you look at the window note you can select multiple programming languages and two versions of wxWidgets. Select Python and wxWidgets 2.8.  Finally press Generate code<em><strong>. (Do NOT name the file wx.py because the import needs wx, save it as window.py or something else).</strong></em></p>
<p><strong>Putting it all together:</strong><br />
Run:</p><pre class="crayon-plain-tag">python window.py</pre><p>And a window with a button will appear. Pressing the button will not do anything. To start a function when pressing the button, we need to define a so called Callback. This can be as simple as:</p><pre class="crayon-plain-tag">def OnButton(self, Event, button_label):
        print "In OnButton:", button_label</pre><p>Finally we bind the button to the callback function using:</p><pre class="crayon-plain-tag">self.button_1.Bind(wx.EVT_BUTTON, self.OnButton )</pre><p>Pressing the button will now write a message to the command line. Instead of the boring command line message, we want to show a message box. This can be done using this command:</p><pre class="crayon-plain-tag">wx.MessageBox( "This is a message.", "Button pressed.");</pre><p>The full code below:</p><pre class="crayon-plain-tag">#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#
# generated by wxGlade 0.6.8 on Fri Jan 23 22:59:56 2015
#

import wx

# begin wxGlade: dependencies
import gettext
# end wxGlade

# begin wxGlade: extracode
# end wxGlade


class MyFrame(wx.Frame):
    def __init__(self, *args, **kwds):
        # begin wxGlade: MyFrame.__init__
        kwds["style"] = wx.DEFAULT_FRAME_STYLE
        wx.Frame.__init__(self, *args, **kwds)
        self.button_1 = wx.Button(self, wx.ID_ANY, _("Hello World!"))
        self.button_1.Bind(wx.EVT_BUTTON, self.OnButton )

        self.__set_properties()
        self.__do_layout()
        # end wxGlade

    def __set_properties(self):
        # begin wxGlade: MyFrame.__set_properties
        self.SetTitle(_("wxWidgets button example. talkera.org/python "))
        # end wxGlade

    def __do_layout(self):
        # begin wxGlade: MyFrame.__do_layout
        sizer_1 = wx.BoxSizer(wx.VERTICAL)
        sizer_1.Add(self.button_1, 0, 0, 0)
        self.SetSizer(sizer_1)
        sizer_1.Fit(self)
        self.Layout()
        # end wxGlade

    def OnButton(event, button_label):
        wx.MessageBox( "This is a message.", "Button pressed.");
  

# end of class MyFrame
if __name__ == "__main__":
    gettext.install("app") # replace with the appropriate catalog name

    app = wx.PySimpleApp(0)
    wx.InitAllImageHandlers()
    frame_1 = MyFrame(None, wx.ID_ANY, "")
    app.SetTopWindow(frame_1)
    frame_1.Show()
    app.MainLoop()</pre><p><a href="/python/wp-content/uploads/2015/01/gui.png"><img class="alignnone size-medium wp-image-73" src="/python/wp-content/uploads/2015/01/gui-300x154.png" alt="wxWidgets gui python" width="300" height="154" /></a></p>
<p>&nbsp;</p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners%2F&amp;linkname=Creating%20a%20gui%20in%20Python%20with%20WxWidgets%20%5Btutorial%20for%20beginners%5D" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners%2F&amp;linkname=Creating%20a%20gui%20in%20Python%20with%20WxWidgets%20%5Btutorial%20for%20beginners%5D" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners%2F&amp;linkname=Creating%20a%20gui%20in%20Python%20with%20WxWidgets%20%5Btutorial%20for%20beginners%5D" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners%2F&amp;linkname=Creating%20a%20gui%20in%20Python%20with%20WxWidgets%20%5Btutorial%20for%20beginners%5D" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners%2F&amp;linkname=Creating%20a%20gui%20in%20Python%20with%20WxWidgets%20%5Btutorial%20for%20beginners%5D" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners%2F&amp;linkname=Creating%20a%20gui%20in%20Python%20with%20WxWidgets%20%5Btutorial%20for%20beginners%5D" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners%2F&amp;title=Creating%20a%20gui%20in%20Python%20with%20WxWidgets%20%5Btutorial%20for%20beginners%5D" id="wpa2a_12"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/creating-a-gui-in-python-with-wxwidgets-tutorial-for-beginners/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>An Introduction to Building Quantum Computing Applications with Python</title>
		<link>https://talkera.org/python/an-introduction-to-building-quantum-computing-applications-with-python/</link>
		<comments>https://talkera.org/python/an-introduction-to-building-quantum-computing-applications-with-python/#comments</comments>
		<pubDate>Tue, 20 Jan 2015 15:06:46 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[Quantum computing]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Quantum]]></category>
		<category><![CDATA[qubit]]></category>
		<category><![CDATA[sigmam]]></category>
		<category><![CDATA[sigmap]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=53</guid>
		<description><![CDATA[So we want to make a quantum application with Python, but since we do not own any quantum computer we need to have a simulator first. Simulation will not have the same performance as an actual quantum computer but we will be able to run applications. We have a choice from three simulators:  PyQu , [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>So we want to make a quantum application with Python, but since we do not own any quantum computer we need to have a simulator first. Simulation will not have the same performance as an actual quantum computer but we will be able to run applications. We have a choice from three simulators:  <a href="https://code.google.com/p/pyqu/" target="_blank">PyQu</a> , <a href="https://code.google.com/p/qutip/" target="_blank">QuTip</a> and <a href="http://www.stahlke.org/dan/qitensor/" target="_blank">Qitensor</a>.  We decided to pick QuTip as it has a very large code base and as it has the most recent changes.  PyQu hasn&#8217;t been updated since 2010 and Qitensor since a year or so.</p>
<p><strong>Installing</strong><br />
We use a Unix machine in this tutorial, but you should be fine with any other operating system. Install using:</p><pre class="crayon-plain-tag">sudo add-apt-repository ppa:jrjohansson/qutip-releases
sudo apt-get update
sudo apt-get install python-qutip</pre><p>We then start Python from the command line and type the commands listed below ( &gt;&gt;&gt; ).</p><pre class="crayon-plain-tag">$ python
Python 2.7.6 (default, Mar 22 2014, 22:59:38) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
&gt;&gt;&gt; from qutip import *
&gt;&gt;&gt; about()

QuTiP: Quantum Toolbox in Python
Copyright (c) 2011 and later.
Paul D. Nation &amp; Robert J. Johansson

QuTiP Version:      3.1.0
Numpy Version:      1.8.2
Scipy Version:      0.13.3
Cython Version:     0.20.1post0
Matplotlib Version: 1.3.1
Fortran mcsolver:   True
scikits.umfpack:    False
Python Version:     2.7.6
Platform Info:      Linux (i686)
Installation path:  /usr/lib/python2.7/dist-packages/qutip</pre><p>This indicates that Qutip has been correctly installed.</p>
<p><strong>The Quantum data structure</strong><br />
In quantum systems we need a data structure that is capable of encapsulating the properties of a quantum operator and ket/bra vectors, we use the Qobj data structure for that. In other words, to effectively simulate a quantum application we need to use the appropriate data structure.  Consider the example below:</p><pre class="crayon-plain-tag">#!/usr/bin/env python
from qutip import *
from scipy import *

r = rand(4, 4)
print Qobj(r)</pre><p>And execute with:</p><pre class="crayon-plain-tag">python quantum.py</pre><p>This will output the quantum object:</p><pre class="crayon-plain-tag">Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isherm = False
Qobj data =
[[ 0.25529374  0.75548592  0.85680266  0.1438253 
 [ 0.75070138  0.68628867  0.97435624  0.77396516]
 [ 0.69819458  0.81714756  0.2604015   0.69051901]
 [ 0.0898242   0.05292657  0.49134431  0.4433644 ]]</pre><p>If you want to specify user input yourself you could use:</p><pre class="crayon-plain-tag">#!/usr/bin/env python
from qutip import *
from scipy import *

x = array([[1],[2],[3],[4],[5]])
q = Qobj(x)
print q</pre><p>This quantum object will simply hold your user given data:</p><pre class="crayon-plain-tag">Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket
Qobj data =
[[ 1.]
 [ 2.]
 [ 3.]
 [ 4.]
 [ 5.]]</pre><p><strong> Quantum states and operators</strong><br />
A quantum system is not a simple two-level system, it has multiple states.  QuTip includes some predefined states and quantum operators which are <a href="http://qutip.org/docs/2.2.0/guide/guide-basics.html#first-things-first" target="_blank">listed here. </a></p>
<p><strong>Qubits and operators</strong><br />
We create a Qubit to hold data. Th Qubit is the quantum analogue of the classical bit. Unlike traditional bits, the qubit can be in a superposition of both states at the same time, a property which is fundamental to quantum computing. The code below will create a qubit:</p><pre class="crayon-plain-tag">#!/usr/bin/env python
from qutip import *
from scipy import *

spin = basis(2, 0)
print spin</pre><p>You can now apply quantum system operators on the qubit:</p><pre class="crayon-plain-tag">#!/usr/bin/env python
from qutip import *
from scipy import *

spin = basis(2, 0)
print sigmam() * spin
print sigmap() * spin</pre><p><strong>Combining qubits</strong><br />
To describe the states of two coupled qubits we need to take the tensor product of the state vectors for each of the system components. Let us try that:</p><pre class="crayon-plain-tag">#!/usr/bin/env python
from qutip import *
from scipy import *

q1 = basis(2, 0)
q2 = basis(2,0)

print q1
print q2
print tensor(q1,q2)</pre><p>The output we will get is:</p><pre class="crayon-plain-tag">Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket
Qobj data =
[[ 1.]
 [ 0.]]
Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket
Qobj data =
[[ 1.]
 [ 0.]]
Quantum object: dims = [[2, 2], [1, 1]], shape = [4, 1], type = ket
Qobj data =
[[ 1.]
 [ 0.]
 [ 0.]
 [ 0.]]</pre><p><strong>Whats next?</strong><br />
We have built some very simply quantum applications using this simple introduction. Perhaps you want to create an actually useful application, if so you could study more about quantum computing and complete the tutorial at <a href="http://qutip.org/docs/2.2.0/index.html" target="_blank">http://qutip.org/docs/2.2.0/index.html</a></p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fan-introduction-to-building-quantum-computing-applications-with-python%2F&amp;linkname=An%20Introduction%20to%20Building%20Quantum%20Computing%20Applications%20with%20Python" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fan-introduction-to-building-quantum-computing-applications-with-python%2F&amp;linkname=An%20Introduction%20to%20Building%20Quantum%20Computing%20Applications%20with%20Python" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fan-introduction-to-building-quantum-computing-applications-with-python%2F&amp;linkname=An%20Introduction%20to%20Building%20Quantum%20Computing%20Applications%20with%20Python" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fan-introduction-to-building-quantum-computing-applications-with-python%2F&amp;linkname=An%20Introduction%20to%20Building%20Quantum%20Computing%20Applications%20with%20Python" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fan-introduction-to-building-quantum-computing-applications-with-python%2F&amp;linkname=An%20Introduction%20to%20Building%20Quantum%20Computing%20Applications%20with%20Python" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fan-introduction-to-building-quantum-computing-applications-with-python%2F&amp;linkname=An%20Introduction%20to%20Building%20Quantum%20Computing%20Applications%20with%20Python" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fan-introduction-to-building-quantum-computing-applications-with-python%2F&amp;title=An%20Introduction%20to%20Building%20Quantum%20Computing%20Applications%20with%20Python" id="wpa2a_14"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/an-introduction-to-building-quantum-computing-applications-with-python/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building an IRC (ro)bot</title>
		<link>https://talkera.org/python/building-an-irc-bot/</link>
		<comments>https://talkera.org/python/building-an-irc-bot/#comments</comments>
		<pubDate>Tue, 13 Jan 2015 15:53:53 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[Networking]]></category>
		<category><![CDATA[irc]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[sockets]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=39</guid>
		<description><![CDATA[There are tons of (ro)bots out there for IRC (Internet Relay Chat). So how do you start and build one in Python, just for fun? You will need a program that connects with an IRC server and acts like a traditional IRC client.  IRC servers never ask for any type of complicated human verification such [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>There are tons of (ro)bots out there for <a href="https://en.wikipedia.org/wiki/Internet_Relay_Chat" target="_blank">IRC (Internet Relay Chat)</a>. So how do you start and build one in Python, just for fun?</p>
<p>You will need a program that connects with an IRC server and acts like a traditional IRC client.  IRC servers never ask for any type of complicated human verification such as solving captchas, which is why we can simply connect with a script. The script itself will use network<em> sockets,  </em>a library that is often used to provide network interactions in many programming languages including Python and C/C++.</p>
<p>To communicate with an IRC server, you need to use the IRC protocol.  The IRC protocol has distinct messages such as PRIVMSG, USER, NICK and JOIN. If you are curious, you could read<a href="http://www.irc.org/tech_docs/rfc1459.html" target="_blank"> the entire protocol</a>. But following this tutorial may be a lot simpler <img src="/python/wp-includes/images/smilies/icon_wink.gif" alt=";)" class="wp-smiley" /> Authentication is achieved using only a few steps:</p>
<p>The IRC protocol is a layer on top of the IP protocol.   To create a socket we use the command:</p><pre class="crayon-plain-tag">irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)</pre><p><code></code>socket.AF_INET tells the library to use the network protocol <a title="IPv4" href="https://en.wikipedia.org/wiki/IPv4">IPv4.</a>   The second argument tells the library to use stream sockets, which are traditionally implemented on the TCP protocol. (IRC works over TCP/IP). We then must use the commands to authenticate with the server:</p><pre class="crayon-plain-tag">USER botname botname botname: phrase
NICK botname
JOIN #channel</pre><p>Sometimes the IDENT command is neccesary too. Summing up, we get this class (save it as irc.py):</p><pre class="crayon-plain-tag">import socket
import sys


class IRC:

    irc = socket.socket()
  
    def __init__(self):  
        self.irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    def send(self, chan, msg):
        self.irc.send("PRIVMSG " + chan + " " + msg + "\n")

    def connect(self, server, channel, botnick):
        #defines the socket
        print "connecting to:"+server
        self.irc.connect((server, 6667))                                                         #connects to the server
        self.irc.send("USER " + botnick + " " + botnick +" " + botnick + " :This is a fun bot!\n") #user authentication
        self.irc.send("NICK " + botnick + "\n")               
        self.irc.send("JOIN " + channel + "\n")        #join the chan

    def get_text(self):
        text=self.irc.recv(2040)  #receive the text

        if text.find('PING') != -1:                      
            self.irc.send('PONG ' + text.split() [1] + '\r\n') 

        return text</pre><p>Now that we have the network connectivity class, we can use it as an instance.  We will keep our (ro)bot simple for explanatory purposes. The bot will reply &#8220;Hello!&#8221; if it gets the message &#8220;hello&#8221; in the channel it resides.</p><pre class="crayon-plain-tag">from irc import *
import os
import random

channel = "#testit"
server = "irc.freenode.net"
nickname = "reddity"

irc = IRC()
irc.connect(server, channel, nickname)


while 1:
    text = irc.get_text()
    print text
 
    if "PRIVMSG" in text and channel in text and "hello" in text:
        irc.send(channel, "Hello!")</pre><p>Save it as bot.py and run with <em>python bot.py</em>. Connect with a traditional irc client (mirc,hexchat,irsii) to the the channel and observe the experiment has worked! You can now extend it with any cool features you can imagine.</p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-irc-bot%2F&amp;linkname=Building%20an%20IRC%20%28ro%29bot" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-irc-bot%2F&amp;linkname=Building%20an%20IRC%20%28ro%29bot" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-irc-bot%2F&amp;linkname=Building%20an%20IRC%20%28ro%29bot" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-irc-bot%2F&amp;linkname=Building%20an%20IRC%20%28ro%29bot" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-irc-bot%2F&amp;linkname=Building%20an%20IRC%20%28ro%29bot" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-irc-bot%2F&amp;linkname=Building%20an%20IRC%20%28ro%29bot" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fbuilding-an-irc-bot%2F&amp;title=Building%20an%20IRC%20%28ro%29bot" id="wpa2a_16"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/building-an-irc-bot/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating a gmail wordcloud</title>
		<link>https://talkera.org/python/creating-a-gmail-wordcloud/</link>
		<comments>https://talkera.org/python/creating-a-gmail-wordcloud/#comments</comments>
		<pubDate>Sun, 11 Jan 2015 20:19:42 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[gmail]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=28</guid>
		<description><![CDATA[I have created a python program that generates a wordcloud based on your gmail account. The output may look something like this depending on the contents of your emails: First you will need a small script that interacts with the gmail service. We have created a small script that interact with gmail. It relies on [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>I have created a python program that <strong>generates a wordcloud based on your gmail</strong> account. The output may look something like this depending on the contents of your emails:</p>
<p><a href="/python/wp-content/uploads/2015/01/gmail2.jpg"><img class="size-medium wp-image-33" src="/python/wp-content/uploads/2015/01/gmail2-300x150.jpg" alt="gmail" width="300" height="150" /></a></p>
<p>First you will need a small script that interacts with the gmail service. We have created a small script that interact with gmail. It relies on <a href="https://github.com/thedjpetersen/gmaillib" target="_blank">gmaillib</a> installed and you will need to set: allow &#8220;less-secure&#8221; applications to access gmail server:  <a href="https://www.google.com/settings/security/lesssecureapps" target="_blank">https://www.google.com/settings/security/lesssecureapps</a></p>
<p><strong>Gmail example:</strong></p><pre class="crayon-plain-tag">#!/usr/bin/env python
import gmaillib
from collections import Counter


def getMails(cnt,account, start,amount):
  emails = account.inbox(start, amount)

  for email in emails:
    cnt[email.sender_addr] += 1

amountOfMails = 100
cnt = Counter()
username = raw_input("Gmail account: ")
password = raw_input("Password: ")

account = gmaillib.account(username, password)

getMails(cnt,account,0,amountOfMails)
print cnt</pre><p>If this script runs successfully you have almost all requirements installed. You will also need the library called <a href="https://github.com/amueller/word_cloud" target="_blank">wordcloud</a>. We rebuild the system such that we get one long string containing the message bodies, which we feed as input to the wordcloud instance. The variable amount contains the number of mails to fetch. We have set it to 100 but you could set it to all messages using  get_inbox_count() or you could simply fetch all emails of the last week.</p>
<p><strong>Final program:</strong></p><pre class="crayon-plain-tag">#!/usr/bin/env python
import gmaillib
from collections import Counter
from wordcloud import WordCloud
import matplotlib.pyplot as plt

amount = 100
cnt = Counter()
username = raw_input("Gmail account: ")
password = raw_input("Password: ")

account = gmaillib.account(username, password)

emails = account.inbox(0, amount)

data = ""
for email in emails:
  data = data + str(email.body)

wordcloud = WordCloud().generate(data)
plt.imshow(wordcloud)
plt.axis("off")
plt.show()</pre><p></p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gmail-wordcloud%2F&amp;linkname=Creating%20a%20gmail%20wordcloud" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gmail-wordcloud%2F&amp;linkname=Creating%20a%20gmail%20wordcloud" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gmail-wordcloud%2F&amp;linkname=Creating%20a%20gmail%20wordcloud" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gmail-wordcloud%2F&amp;linkname=Creating%20a%20gmail%20wordcloud" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gmail-wordcloud%2F&amp;linkname=Creating%20a%20gmail%20wordcloud" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gmail-wordcloud%2F&amp;linkname=Creating%20a%20gmail%20wordcloud" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Fcreating-a-gmail-wordcloud%2F&amp;title=Creating%20a%20gmail%20wordcloud" id="wpa2a_18"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/creating-a-gmail-wordcloud/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Requests: HTTP for Humans</title>
		<link>https://talkera.org/python/requests-http-for-humans/</link>
		<comments>https://talkera.org/python/requests-http-for-humans/#comments</comments>
		<pubDate>Tue, 23 Dec 2014 15:32:06 +0000</pubDate>
		<dc:creator><![CDATA[admin]]></dc:creator>
				<category><![CDATA[Web]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[web]]></category>

		<guid isPermaLink="false">https://talkera.org/python/?p=5</guid>
		<description><![CDATA[If you want to request data from webservers, the traditional way to do that in Python is using the urllib library. While this library is effective, you could easily create more complexity than needed when building something. Is there another way? Requests is an Apache2 Licensed HTTP library, written in Python. It&#8217;s powered by httplib and urllib3, [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>If you want to request data from webservers, the traditional way to do that in Python is using the <em>urllib</em> library. While this library is effective, you could easily create more complexity than needed when building something. Is there another way?</p>
<p><a href="https://github.com/kennethreitz/requests" target="_blank">Requests</a> is an Apache2 Licensed HTTP library, written in Python. It&#8217;s powered by httplib and <a href="https://github.com/shazow/urllib3">urllib3</a>, but it does all the hard work and crazy hacks for you.</p>
<p>To install type:</p><pre class="crayon-plain-tag">git clone https://github.com/kennethreitz/requests.git
cd requests
sudo python setup.py install</pre><p>The Requests library is now installed. We will list some examples below:</p>
<p><strong>Grabbing raw html using HTTP/HTTPS requests</strong><br />
We can now query a website as :</p><pre class="crayon-plain-tag">import requests
r = requests.get('https://talkera.org/python/')
print r.content</pre><p>Save it and run with:</p><pre class="crayon-plain-tag">python website.py</pre><p>It will output the raw HTML code.</p>
<p><strong>Download binary image using Python</strong></p><pre class="crayon-plain-tag">from PIL import Image
from StringIO import StringIO
import requests

r = requests.get('http://1.bp.blogspot.com/_r-MQun1PKUg/SlnHnaLcw6I/AAAAAAAAA_U$
i = Image.open(StringIO(r.content))
i.show()</pre><p><a href="/python/wp-content/uploads/2014/12/python.png"><img class="size-medium wp-image-12" src="/python/wp-content/uploads/2014/12/python-300x292.png" alt="python" width="300" height="292" /></a></p>
<p>An image retrieved using python</p>
<p><strong>Website status code (is the website online?)</strong></p><pre class="crayon-plain-tag">import requests
r = requests.get('https://talkera.org/python/')
print r.status_code</pre><p>This returns 200 (OK). A list of status codes can be found here: <a href="https://en.wikipedia.org/wiki/List_of_HTTP_status_codes" target="_blank">https://en.wikipedia.org/wiki/List_of_HTTP_status_codes</a></p>
<p><strong>Retrieve JSON from a webserver </strong><br />
You can easily grab a JSON object from a webserver.</p><pre class="crayon-plain-tag">import requests

import requests
r = requests.get('https://api.github.com/events')
print r.json()</pre><p><strong>HTTP Post requests using Python</strong></p><pre class="crayon-plain-tag">from StringIO import StringIO
import requests

payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.post("http://httpbin.org/post", data=payload)
print(r.text)</pre><p><strong>SSL verification, verify certificates using Python</strong></p><pre class="crayon-plain-tag">from StringIO import StringIO
import requests
print requests.get('https://github.com', verify=True)</pre><p>&nbsp;</p>
<p><a class="a2a_button_facebook" href="http://www.addtoany.com/add_to/facebook?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Frequests-http-for-humans%2F&amp;linkname=Requests%3A%20HTTP%20for%20Humans" title="Facebook" rel="nofollow" target="_blank"></a><a class="a2a_button_twitter" href="http://www.addtoany.com/add_to/twitter?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Frequests-http-for-humans%2F&amp;linkname=Requests%3A%20HTTP%20for%20Humans" title="Twitter" rel="nofollow" target="_blank"></a><a class="a2a_button_google_plus" href="http://www.addtoany.com/add_to/google_plus?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Frequests-http-for-humans%2F&amp;linkname=Requests%3A%20HTTP%20for%20Humans" title="Google+" rel="nofollow" target="_blank"></a><a class="a2a_button_reddit" href="http://www.addtoany.com/add_to/reddit?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Frequests-http-for-humans%2F&amp;linkname=Requests%3A%20HTTP%20for%20Humans" title="Reddit" rel="nofollow" target="_blank"></a><a class="a2a_button_stumbleupon" href="http://www.addtoany.com/add_to/stumbleupon?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Frequests-http-for-humans%2F&amp;linkname=Requests%3A%20HTTP%20for%20Humans" title="StumbleUpon" rel="nofollow" target="_blank"></a><a class="a2a_button_pinterest" href="http://www.addtoany.com/add_to/pinterest?linkurl=http%3A%2F%2Ftalkera.org%2Fpython%2Frequests-http-for-humans%2F&amp;linkname=Requests%3A%20HTTP%20for%20Humans" title="Pinterest" rel="nofollow" target="_blank"></a><a class="a2a_dd a2a_target addtoany_share_save" href="https://www.addtoany.com/share_save#url=http%3A%2F%2Ftalkera.org%2Fpython%2Frequests-http-for-humans%2F&amp;title=Requests%3A%20HTTP%20for%20Humans" id="wpa2a_20"></a></p>]]></content:encoded>
			<wfw:commentRss>https://talkera.org/python/requests-http-for-humans/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
