doc:appunti:prog:python_unicode
Differences
This shows you the differences between two versions of the page.
Both sides previous revisionPrevious revisionNext revision | Previous revisionNext revisionBoth sides next revision | ||
doc:appunti:prog:python_unicode [2012/12/03 11:42] – [Codifica implicita della print] niccolo | doc:appunti:prog:python_unicode [2013/01/28 10:05] – [Nomi di file e directory] niccolo | ||
---|---|---|---|
Line 7: | Line 7: | ||
===== Input: lettura da database ===== | ===== Input: lettura da database ===== | ||
+ | Si assume che nel database i campi testo siano codificati UTF-8. Sarebbe opportuno che il charset del database sia dichiarato UTF-8 in fase di creazione dello stesso; con PostgreSQL si tratta dell' | ||
+ | |||
+ | Per assicurarsi che Python decodifichi correttamente le stringhe lette da un database: | ||
+ | |||
+ | <code python> | ||
+ | import MySQLdb | ||
+ | conn = MySQLdb.connect(host=' | ||
+ | curs = conn.cursor() | ||
+ | # Not strictly needed: | ||
+ | # | ||
+ | curs.execute(" | ||
+ | rows = curs.fetchall() | ||
+ | for row in rows: | ||
+ | field0 = row[0] | ||
+ | print type(field0), | ||
+ | ... | ||
+ | </ | ||
+ | |||
+ | La funzione **'' | ||
+ | |||
+ | Se si omette la dichiarazione del **'' | ||
+ | |||
+ | <code python> | ||
+ | curs.execute(" | ||
+ | curs.execute(" | ||
+ | rows = curs.fetchall() | ||
+ | for row in rows: | ||
+ | field0 = row[0].decode(' | ||
+ | print type(field0), | ||
+ | ... | ||
+ | </ | ||
+ | |||
+ | ===== Input/ | ||
+ | |||
+ | Se si deve comunicare con un programma esterno utilizzando UTF-8 conviene come al solito memorizzare le stringhe in unicode e quindi esplicitare l' | ||
+ | |||
+ | <code python> | ||
+ | text = u" | ||
+ | subproc = subprocess.Popen([" | ||
+ | output, stderr = subproc.communicate(input=text.encode(' | ||
+ | output = output.decode(' | ||
+ | </ | ||
+ | |||
+ | La stringa **'' | ||
===== Output: codifica implicita della print ===== | ===== Output: codifica implicita della print ===== | ||
Line 15: | Line 59: | ||
</ | </ | ||
- | codifica il contenuto di '' | + | codifica il contenuto di '' |
< | < | ||
Line 27: | Line 71: | ||
</ | </ | ||
+ | ===== Nomi di file e directory ===== | ||
+ | |||
+ | Alcune funzioni relative al filesystem potrebbero causare problemi, ad esempio: | ||
+ | |||
+ | <code python> | ||
+ | os.path.isfile(filename) | ||
+ | </ | ||
+ | |||
+ | potrebbe fallire con: | ||
+ | |||
+ | < | ||
+ | UnicodeEncodeError: | ||
+ | </ |
doc/appunti/prog/python_unicode.txt · Last modified: 2015/07/17 09:50 by niccolo