473,804 Members | 2,024 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

[UnicodeEncodeEr ror] Don't know what else to try

Hello

Data that I download from the web seems to be using different code
pages at times, and Python doesn't like this.

Google returned a way to handle this, but I'm still getting an error:
========
print output.decode(' utf-8')
File "C:\Python25\li b\encodings\utf _8.py", line 16, in decode
return codecs.utf_8_de code(input, errors, True)
UnicodeEncodeEr ror: 'ascii' codec can't encode character u'\xe2' in
position 47:
ordinal not in range(128)
========

Here's the code:
========
try:
output = "Different: (%s) %s : %s # %s" %
(id[2],id[3],id[0],id[1])
print output.decode(' utf-8')

except UnicodeDecodeEr ror:

try:
output = "Different: (%s) %s : %s # %s" %
(id[2],id[3],id[0],id[1])
print output.decode(' iso8859-15')

except UnicodeDecodeEr ror:
output = "Different: (%s) %s : %s # %s" %
(id[2],id[3],id[0],id[1])
print output.decode(' cp1252')
========

Am I doing it wrong? Is there something else I should try?

Thank you.
Nov 14 '08 #1
7 5127
print output.decode(' utf-8')
File "C:\Python25\li b\encodings\utf _8.py", line 16, in decode
return codecs.utf_8_de code(input, errors, True)
UnicodeEncodeEr ror: 'ascii' codec can't encode character u'\xe2' in
position 47:
ordinal not in range(128)
Notice that it complains about the 'ascii' codec, when you were using
the utf-8 codec. Also, it complains about *en*coding, when you try
decoding.
For this, there could be two possible causes:

1. output is already a Unicode object - decoding it is not a meaningful
operation. So Python first *en*codes it with ascii, then would decode
it with UTF-8. The first step fails.
2. decoding from utf-8 works fine. It then tries to print output, which
requires an encoding. By default, it encodes as ascii, which fails.
========

Here's the code:
========
try:
output = "Different: (%s) %s : %s # %s" %
(id[2],id[3],id[0],id[1])
Add
print type(output)
here. If it says "unicode", reconsider the next line
print output.decode(' utf-8')
Regards,
Martin
Nov 14 '08 #2
On Fri, 14 Nov 2008 11:01:27 +0100, "Martin v. Löwis"
<ma****@v.loewi s.dewrote:
>Add
print type(output)
here. If it says "unicode", reconsider the next line
> print output.decode(' utf-8')
In case the string fetched from a web page turns out not to be Unicode
and Python isn't happy, what is the right way to handle this, know
what codepage is being used?

Thank you.
Nov 14 '08 #3
On Fri, 14 Nov 2008 14:57:42 +0100, Gilles Ganault wrote:
On Fri, 14 Nov 2008 11:01:27 +0100, "Martin v. Löwis"
<ma****@v.loewi s.dewrote:
>>Add
print type(output)
here. If it says "unicode", reconsider the next line
>> print output.decode(' utf-8')

In case the string fetched from a web page turns out not to be Unicode
and Python isn't happy, what is the right way to handle this, know what
codepage is being used?
How do you fetch the data? If you simply download it with `urllib` or
`urllib` you never get `unicode` but ordinary `str`\s. The you have to
figure out the encoding by looking at the headers from the server and/or
looking at the fetched data if it contains hints.

And when ``print``\ing you should explicitly *encode* the data again
because sooner or later you will come across a `stdout` where Python
can't determine what the process at the other end expects, for example if
output is redirected to a file.

Ciao,
Marc 'BlackJack' Rintsch
Nov 14 '08 #4
Gilles Ganault wrote:
On Fri, 14 Nov 2008 11:01:27 +0100, "Martin v. Löwis"
<ma****@v.loewi s.dewrote:
>Add
print type(output)
here. If it says "unicode", reconsider the next line
>> print output.decode(' utf-8')

In case the string fetched from a web page turns out not to be Unicode
and Python isn't happy, what is the right way to handle this, know
what codepage is being used?
Can you first please report what happened when you add the print statement?

Thanks,
Martin
Nov 14 '08 #5
On Fri, 14 Nov 2008 17:39:00 +0100, "Martin v. Löwis"
<ma****@v.loewi s.dewrote:
>Can you first please report what happened when you add the print statement?
Thanks guys, I found how to handle this:

===========
for id in rows:
#Says Unicode, but it's actually not
#print type(id[1])
#<type 'unicode'>

try:
print id[1];
except UnicodeEncodeEr ror:
print "Not unicode"
try:
print id[1].encode('iso885 9-15')
print "iso"
except UnicodeEncodeEr ror:
print id[1].encode('cp1252 ')
print "Windows"
===========

Thank you.
Nov 15 '08 #6
On Sat, 15 Nov 2008 14:12:42 +0100, Gilles Ganault wrote:
On Fri, 14 Nov 2008 17:39:00 +0100, "Martin v. Löwis"
<ma****@v.loewi s.dewrote:
>>Can you first please report what happened when you add the print
statement?

Thanks guys, I found how to handle this:

===========
for id in rows:
#Says Unicode, but it's actually not
#print type(id[1])
#<type 'unicode'>
If it says `unicode` *it is* `unicode`.
try:
print id[1];
except UnicodeEncodeEr ror:
print "Not unicode"
But it *is* `unicode` if `type()` says so!

Your code still fails when ``id[1]`` can't be encoded in `sys.encoding`,
'iso8859-15', or 'cp1252'. Even worse: The output may be even encoded in
different encodings this way. That's garbage you can't decode properly
with one encoding anymore.

A clean solution would be just one ``print`` with a call of `encode()`
and an explicit encoding. I'd use 'utf-8' as default but give the user
of the program a possibility to make another choice.

Ciao,
Marc 'BlackJack' Rintsch
Nov 15 '08 #7
On Nov 16, 12:12*am, Gilles Ganault <nos...@nospam. comwrote:
On Fri, 14 Nov 2008 17:39:00 +0100, "Martin v. Löwis"

<mar...@v.loewi s.dewrote:
Can you first please report what happened when you add the print statement?

Thanks guys, I found how to handle this:
No you didn't.
>
===========
for id in rows:
* * * * #Says Unicode, but it's actually not
If it's not unicode, what is it? What is your basis for that assertion
(which implies there is a bug in the version of Python that you are
using)? The probability that type() ever become so buggy that it
misreports whether a value is unicode or not, is extremely small.
Further the probability that you or I would be the first to notice the
problem is vanishingly small.
* * * * #print type(id[1])
* * * * #<type 'unicode'>
You didn't reply to Martin's question, instead you are tilting at a
windmill whose probability of existence lies between epsilon and zero.
When you ask for help, you should act on reasonable requests from your
helpers. Here's a reasonable request; insert some more verbose
debugging code:
print 'id[1] is', type(id[1]), repr(id[1])
AND tell us what you see, *before* you try to "fix" it.

For the future, please remember these:
(1) When you are worried about exactly what data some name refers to,
do
print 'name is', type(name), repr(name)
(2) Examine the more plausible sources of error first ... here's a
partial ordering: Ganault, ..., Gates, ..., Guido, God :-)

HTH,
John
Nov 15 '08 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
1680
by: Maurice LING | last post by:
Hi, I'm working on a script that searches a public database and retrives results using SOAP interface. However, it seems that the results may contains unicodes. When I try to pump the results into Firebird database using kinterbasdb module, some results will give me a UnicodeEncodeError. From what I've gathered, it looks like the conversion from the results from SOAP interface to string results in the error.
1
2493
by: Bob Swerdlow | last post by:
My application is getting this error on Windows XP (works fine on Mac OS X) when it calls os.path.expanduser: UnicodeEncodeError: 'ascii' codec can't encode characters in position 52-56: ordinal not in range(128) The code was built with Python 2.3.4. I found referenes to Path 957650, but I'm not familiar with how such fixes are processed. Is there a patch I can add to fix this? How do I know what version of Python it is fixed in -...
2
12436
by: Francach | last post by:
Hi, I don't know what I'm doing wrong here. I''m using Python 2.4 and py2exe. I get he following error: Traceback (most recent call last): File "notegui.pyc", line 34, in OnClose File "brain.pyc", line 61, in setNote File "points.pyc", line 151, in setNote File "point.pyc", line 100, in writeNote
0
17826
by: Nashat Wanly | last post by:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnaskdr/html/askgui06032003.asp Don't Lock Type Objects! Why Lock(typeof(ClassName)) or SyncLock GetType(ClassName) Is Bad Rico Mariani, performance architect for the Microsoft® .NET runtime and longtime Microsoft developer, mentioned to Dr. GUI in an e-mail conversation recently that a fairly common practice (and one that's, unfortunately, described in some of our...
19
3884
by: LP | last post by:
I am using (trying to) CR version XI, cascading parameters feature works it asks user to enter params. But if page is resubmitted. It prompts for params again. I did set ReuseParameterValuesOnRefresh="True" in a viewer, but it still doesn't work. Did anyone run into this problem. What's the solution? Please help. Thank you
8
1355
by: Simon Willison | last post by:
Hi all, I have an API design question. I'm writing a function that can either succeed or fail. Most of the time the code calling the function won't care about the reason for the failure, but very occasionally it will. I can see a number of ways of doing this, but none of them feel aesthetically pleasing: 1.
3
3948
by: erikcw | last post by:
Hi all, I'm trying to parse an email message, but am running into this exception. Traceback (most recent call last): File "wa.py", line 336, in ? main() File "wa.py", line 332, in main print out
2
1773
by: xianwei | last post by:
First, typedef struct pair { Node *parent; Node *child; } Pair; static Pair SeekItem(cosnt Item *pI, const Tree *pTree) { Pair look;
2
3946
by: nikosk | last post by:
I just spent a whole day trying to read an xml file and I got stuck with the following error: Exception Type: UnicodeEncodeError Exception Value: 'charmap' codec can't encode characters in position 164-167: character maps to <undefined> Exception Location: C:\Python25\lib\encodings\cp1252.py in encode, line 12 The string that could not be encoded/decoded was: H_C="ÊÉÍÁ" A_C
0
9711
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9593
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10595
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10343
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10335
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10088
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9169
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
4306
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3001
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.