Utf-8 text from MySQL not showing in IPython Notebook

I'm new to programming, but I know like Google, so I dare ask you for help on this after a lot of trial and error.

I have a MySQL database (db name: text, table name: text) with utf-8 (Swedish) encoded text that I want to extract into an IPython Notebook using mysql-python (MySQLdb) for further processing.

I have read the python documentation about Unicode and UTF-8 ( http://docs.python.org/2/howto/unicode.html ) but I couldn't find any specific code examples, although this should be a very trivial problem.

I just want the Swedish text to be displayed in IPython Notebook with special characters åäö etc. As you can see, I have added more or less every piece of code I have found on the Internet regarding Unicode and UTF-8, but I cannot figure out where I am doing the error (s)?

Can anyone help me?

# -*- coding: utf-8 -*-
import MySQLdb
db = MySQLdb.connect('localhost', 'user', 'password', 'text', charset='utf8', use_unicode=False)
db.set_character_set('utf8')
cursor = db.cursor()
cursor.execute('SET NAMES utf8')
cursor.execute('SET CHARACTER SET utf8')
cursor.execute('SELECT title, body FROM text LIMIT 5') 
result=cursor.fetchall()
 print result

      

Update: This is what I get from the Print statement: (('F \ xc3 \ xb6rsta rubriken', 'H \ xc3 \ xa4r \ xc3 \ xa4r lite text p \ xc3 \ xa5 svenska'), ('Andra rubriken', 'Ytterligare lite text p \ xc3 \ xa5 ett annat spr \ xc3 \ xa5k'))

+3


source to share


1 answer


You are printing the result of calling the cursor, which is a tuple; and you define its Python representation.

If you go through it, you will see the expected results:



>>> for i in result:
...    print "{} {}".format(*i)
... 
Första rubriken Här är lite text på svenska
Andra rubriken Ytterligare lite text på ett annat språk

      

If your output doesn't match the above, it means your terminal doesn't support UTF-8.

+2


source







All Articles