473,699 Members | 2,506 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

unicode to ascii converting

Hello tlistmembers,

I am using the encoding function to convert unicode to ascii. At one point
this code was working just fine, however, now it has broken.

I am reading a text file that has is in unicode (I am unsure of which
flavour or bit depth). as I read in the file one line at a time
(readlines()) it converts to ascii. Simple enough. At the same time I am
copressing to bz2 with the bz2 module but that works just fine. The code
is and error reported appears below. I am unsure what to do.

I assume that because it is reporting that ordinal is not in range, that
something to do with the character width that I am reading?

Peter W.

def encode_file(fil e_path, encode_type, compress='N'):
"""
Changes encoding of file
"""
new_encode = encode_type
old_file_path = file_path + '.old'
new_file_path = file_path
os.rename(file_ path,old_file_p ath)
file_in = file(old_file_p ath,'r')

if compress == 'Y' or compress == 'y':
bz_file_path = file_path + '.bz2'
bz_file_out = bz2.BZ2File(bz_ file_path, 'w')
for line in file_in.readlin es():
bz_file_out.wri te(line.encode( new_encode))
bz_file_out.clo se()

else:
file_out = file(file_path, 'w')
for line in file_in.readlin es():
file_out.write( line.encode(new _encode))
file_out.close( )

file_in.close()
os.remove(old_f ile_path)

ERROR Reported:

Parsing
X:\GenomeQuebec _repository\mic roarray\HIS\M15 K\Step_1_reposi tory\HISH0224.t xt
Traceback (most recent call last):
File "C:\Program Files\ActiveSta te Komodo 2.5\callkomodo\ kdb.py", line
433, in _do_start
self.kdb.run(co de_ob, locals, locals)
File "C:\Python23\li b\bdb.py", line 350, in run
exec cmd in globals, locals
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 158, in ?
main()
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 75, in main
encode_file(fil eToProcess, options.encode, 'Y')
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 144, in encode_file
bz_file_out.wri te(line.encode( new_encode))
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xff in position 0:
ordinal not in range(128)

Jul 18 '05 #1
12 10693

"Peter Wilkinson" <pw********@vid eotron.ca> wrote in message
news:ma******** *************** *************** @python.org...
Hello tlistmembers,

I am using the encoding function to convert unicode to ascii. At one point
this code was working just fine, however, now it has broken.

I am reading a text file that has is in unicode (I am unsure of which
flavour or bit depth). as I read in the file one line at a time
(readlines()) it converts to ascii. Simple enough. At the same time I am
copressing to bz2 with the bz2 module but that works just fine. The code
is and error reported appears below. I am unsure what to do.

I assume that because it is reporting that ordinal is not in range, that
something to do with the character width that I am reading?

Peter W.

def encode_file(fil e_path, encode_type, compress='N'):
"""
Changes encoding of file
"""
new_encode = encode_type
old_file_path = file_path + '.old'
new_file_path = file_path
os.rename(file_ path,old_file_p ath)
file_in = file(old_file_p ath,'r')

if compress == 'Y' or compress == 'y':
bz_file_path = file_path + '.bz2'
bz_file_out = bz2.BZ2File(bz_ file_path, 'w')
for line in file_in.readlin es():
bz_file_out.wri te(line.encode( new_encode))
bz_file_out.clo se()

else:
file_out = file(file_path, 'w')
for line in file_in.readlin es():
file_out.write( line.encode(new _encode))
file_out.close( )

file_in.close()
os.remove(old_f ile_path)

ERROR Reported:

Parsing
X:\GenomeQuebec _repository\mic roarray\HIS\M15 K\Step_1_reposi tory\HISH0224.t x
t Traceback (most recent call last):
File "C:\Program Files\ActiveSta te Komodo 2.5\callkomodo\ kdb.py", line
433, in _do_start
self.kdb.run(co de_ob, locals, locals)
File "C:\Python23\li b\bdb.py", line 350, in run
exec cmd in globals, locals
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 158, in ?
main()
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 75, in main
encode_file(fil eToProcess, options.encode, 'Y')
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 144, in encode_file
bz_file_out.wri te(line.encode( new_encode))
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xff in position 0:
ordinal not in range(128)

I've encountered this problem before and the solution I've come up with a
fix that works but is probably not the best,

def is_ord (strng):
new_text = ''
for i in strng:
if ord(i) > 127:
new_text = new_text + ''
else:
new_text = new_text + i
return new_text

#Then just,

text_from_file = is_ord(text_fro m_file)

Tom
Jul 18 '05 #2
Thanks Tom B.,

I will try that for now ....

It would be good to find out _why_ this happens in the first place. I will
keep do a little searching on this for a few days.
Peter W.
At 02:04 PM 8/6/2004, Tom B. wrote:
"Peter Wilkinson" <pw********@vid eotron.ca> wrote in message
news:ma******* *************** *************** *@python.org...
Hello tlistmembers,

I am using the encoding function to convert unicode to ascii. At one point
this code was working just fine, however, now it has broken.

I am reading a text file that has is in unicode (I am unsure of which
flavour or bit depth). as I read in the file one line at a time
(readlines()) it converts to ascii. Simple enough. At the same time I am
copressing to bz2 with the bz2 module but that works just fine. The code
is and error reported appears below. I am unsure what to do.

I assume that because it is reporting that ordinal is not in range, that
something to do with the character width that I am reading?

Peter W.

def encode_file(fil e_path, encode_type, compress='N'):
"""
Changes encoding of file
"""
new_encode = encode_type
old_file_path = file_path + '.old'
new_file_path = file_path
os.rename(file_ path,old_file_p ath)
file_in = file(old_file_p ath,'r')

if compress == 'Y' or compress == 'y':
bz_file_path = file_path + '.bz2'
bz_file_out = bz2.BZ2File(bz_ file_path, 'w')
for line in file_in.readlin es():
bz_file_out.wri te(line.encode( new_encode))
bz_file_out.clo se()

else:
file_out = file(file_path, 'w')
for line in file_in.readlin es():
file_out.write( line.encode(new _encode))
file_out.close( )

file_in.close()
os.remove(old_f ile_path)

ERROR Reported:

Parsing

X:\GenomeQuebe c_repository\mi croarray\HIS\M1 5K\Step_1_repos itory\HISH0224. tx
t
Traceback (most recent call last):
File "C:\Program Files\ActiveSta te Komodo 2.5\callkomodo\ kdb.py", line
433, in _do_start
self.kdb.run(co de_ob, locals, locals)
File "C:\Python23\li b\bdb.py", line 350, in run
exec cmd in globals, locals
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 158, in ?
main()
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 75, in main
encode_file(fil eToProcess, options.encode, 'Y')
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 144, in encode_file
bz_file_out.wri te(line.encode( new_encode))
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xff in position 0:
ordinal not in range(128)

I've encountered this problem before and the solution I've come up with a
fix that works but is probably not the best,

def is_ord (strng):
new_text = ''
for i in strng:
if ord(i) > 127:
new_text = new_text + ''
else:
new_text = new_text + i
return new_text

#Then just,

text_from_fi le = is_ord(text_fro m_file)

Tom
--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #3
Peter Wilkinson <pw********@vid eotron.ca> writes:
It would be good to find out _why_ this happens in the first place. I
will keep do a little searching on this for a few days.


Most likely because you have characters in that file that are not in the
ASCII character set. ASCII is after all only a very small subset of
unicode. E.g.
u"".encode("as cii") Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeEr ror: 'ascii' codec can't encode character u'\xe4' in position 0: ordinal not in range(128)
If it's OK to lose information, you could use the error argument to
..encode like
u"".encode("as cii", "ignore") ''

or
u"".encode("as cii", "replace")

'?'
Bernhard

--
Intevation GmbH http://intevation.de/
Skencil http://sketch.sourceforge.net/
Thuban http://thuban.intevation.org/
Jul 18 '05 #4
I tried the function, actually this does not seem to work as I expected.

What happens is that the character encoding seems to change in the
following way: placing what is the equivalent of some return character
after each character ... or when I view the file in excel there is a blank
row in between between each row.

Its very strange.

back to the drawing board
At 02:17 PM 8/6/2004, Peter Wilkinson wrote:
Thanks Tom B.,

I will try that for now ....

It would be good to find out _why_ this happens in the first place. I will
keep do a little searching on this for a few days.
Peter W.
At 02:04 PM 8/6/2004, Tom B. wrote:
"Peter Wilkinson" <pw********@vid eotron.ca> wrote in message
news:ma****** *************** *************** **@python.org.. .
> Hello tlistmembers,
>
> I am using the encoding function to convert unicode to ascii. At one point
> this code was working just fine, however, now it has broken.
>
> I am reading a text file that has is in unicode (I am unsure of which
> flavour or bit depth). as I read in the file one line at a time
> (readlines()) it converts to ascii. Simple enough. At the same time I am
> copressing to bz2 with the bz2 module but that works just fine. The code
> is and error reported appears below. I am unsure what to do.
>
> I assume that because it is reporting that ordinal is not in range, that
> something to do with the character width that I am reading?
>
> Peter W.
>
> def encode_file(fil e_path, encode_type, compress='N'):
> """
> Changes encoding of file
> """
> new_encode = encode_type
> old_file_path = file_path + '.old'
> new_file_path = file_path
> os.rename(file_ path,old_file_p ath)
> file_in = file(old_file_p ath,'r')
>
> if compress == 'Y' or compress == 'y':
> bz_file_path = file_path + '.bz2'
> bz_file_out = bz2.BZ2File(bz_ file_path, 'w')
> for line in file_in.readlin es():
> bz_file_out.wri te(line.encode( new_encode))
> bz_file_out.clo se()
>
> else:
> file_out = file(file_path, 'w')
> for line in file_in.readlin es():
> file_out.write( line.encode(new _encode))
> file_out.close( )
>
> file_in.close()
> os.remove(old_f ile_path)
>
> ERROR Reported:
>
> Parsing
>

X:\GenomeQueb ec_repository\m icroarray\HIS\M 15K\Step_1_repo sitory\HISH0224 .tx
t
> Traceback (most recent call last):
> File "C:\Program Files\ActiveSta te Komodo 2.5\callkomodo\ kdb.py", line
> 433, in _do_start
> self.kdb.run(co de_ob, locals, locals)
> File "C:\Python23\li b\bdb.py", line 350, in run
> exec cmd in globals, locals
> File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
> line 158, in ?
> main()
> File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
> line 75, in main
> encode_file(fil eToProcess, options.encode, 'Y')
> File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
> line 144, in encode_file
> bz_file_out.wri te(line.encode( new_encode))
> UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xff in position 0:
> ordinal not in range(128)
>

I've encountered this problem before and the solution I've come up with a
fix that works but is probably not the best,

def is_ord (strng):
new_text = ''
for i in strng:
if ord(i) > 127:
new_text = new_text + ''
else:
new_text = new_text + i
return new_text

#Then just,

text_from_fil e = is_ord(text_fro m_file)

Tom
--
http://mail.python.org/mailman/listinfo/python-list


--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #5
Well this is interestingly annoying:

u"".encode("as cii", "ignore") -> '' # works just fine but as I have
written

aa = ""
aa.encode("asci i","ignore") ->

Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xe4 in position 0:
ordinal not in range(128)

So I am guessing that I don't understand something about the syntax

Peter

At 02:31 PM 8/6/2004, Bernhard Herzog wrote:
Peter Wilkinson <pw********@vid eotron.ca> writes:
It would be good to find out _why_ this happens in the first place. I
will keep do a little searching on this for a few days.


Most likely because you have characters in that file that are not in the
ASCII character set. ASCII is after all only a very small subset of
unicode. E.g.
u"".encode("as cii")Traceback (most recent call last):
File "<stdin>", line 1, in ?
UnicodeEncodeE rror: 'ascii' codec can't encode character u'\xe4' in
position 0: ordinal not in range(128)
If it's OK to lose information, you could use the error argument to
.encode like
u"".encode("as cii", "ignore")''

or
u"".encode("as cii", "replace")

'?'
Bernhard

--
Intevation GmbH http://intevation.de/
Skencil http://sketch.sourceforge.net/
Thuban http://thuban.intevation.org/
--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #6
Peter Wilkinson wrote:
Hello tlistmembers,

I am using the encoding function to convert unicode to ascii. At one
point this code was working just fine, however, now it has broken.

I am reading a text file that has is in unicode (I am unsure of which
flavour or bit depth). as I read in the file one line at a time
(readlines()) it converts to ascii. Simple enough. At the same time I am
copressing to bz2 with the bz2 module but that works just fine. The
code is and error reported appears below. I am unsure what to do.

I assume that because it is reporting that ordinal is not in range, that
something to do with the character width that I am reading?

Peter W.

def encode_file(fil e_path, encode_type, compress='N'):
"""
Changes encoding of file
"""
new_encode = encode_type
old_file_path = file_path + '.old'
new_file_path = file_path
os.rename(file_ path,old_file_p ath)
file_in = file(old_file_p ath,'r')

if compress == 'Y' or compress == 'y':
bz_file_path = file_path + '.bz2'
bz_file_out = bz2.BZ2File(bz_ file_path, 'w')
for line in file_in.readlin es():
bz_file_out.wri te(line.encode( new_encode))
bz_file_out.clo se()

else:
file_out = file(file_path, 'w')
for line in file_in.readlin es():
file_out.write( line.encode(new _encode))
file_out.close( )

file_in.close()
os.remove(old_f ile_path)

ERROR Reported:

Parsing
X:\GenomeQuebec _repository\mic roarray\HIS\M15 K\Step_1_reposi tory\HISH0224.t xt

Traceback (most recent call last):
File "C:\Program Files\ActiveSta te Komodo 2.5\callkomodo\ kdb.py", line
433, in _do_start
self.kdb.run(co de_ob, locals, locals)
File "C:\Python23\li b\bdb.py", line 350, in run
exec cmd in globals, locals
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 158, in ?
main()
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 75, in main
encode_file(fil eToProcess, options.encode, 'Y')
File "C:\Python23\Li b\site-packages\xBio\S cripts\unicodeT oAscii.py",
line 144, in encode_file
bz_file_out.wri te(line.encode( new_encode))
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xff in position 0:
ordinal not in range(128)


0xff in position 0? If there is a 0xfe is in position 1, I would suspect
your dealing with the Byte Order Mark for a UTF-16 encoded file (UTF-16
LE to be precise). What happens if you skip the first 2 bytes of the file?

--
Vincent Wehren
Jul 18 '05 #7
Peter Wilkinson wrote:
UnicodeDecodeEr ror: 'ascii' codec can't decode byte 0xff in position 0:
ordinal not in range(128)


That error actually says what happened: You have the byte with the
numeric value 0xff in the input, and the ASCII (American Standard
Code for Information Interchange) converter cannot convert that
into a Unicode character. This is because ASCII is a 7-bit character
set, i.e. it goes from 0..127. 0xFF is 255, so it is out of range.

Now, the line triggering this is

bz_file_out.wri te(line.encode( new_encode))

and it invokes *encode*, not *decode*. Why would it give a decode error
then?

Because:

decode: take a byte string, return a Unicode string
encode: take a Unicode string, take a byte string

So line should be a Unicode string, for .encode to be a meaningful thing
to do. Unfortunately, Python supports .encode also for byte strings.
If new_encode defines a character encoding, this does

class str:
def encode(self, encoding):
unistr = unicode(self)
return unistr.encode(e ncoding)

So it first tries to convert the current string into unicode, which
uses the system default encoding, which is us-ascii. Hence the error.

HTH,
Martin
Jul 18 '05 #8
thanks for the clear explanation.

I modified my code and now this works :)
Peter
At 03:46 PM 8/6/2004, Martin v. Lwis wrote:
Peter Wilkinson wrote:
UnicodeDecode Error: 'ascii' codec can't decode byte 0xff in position 0:
ordinal not in range(128)


That error actually says what happened: You have the byte with the numeric
value 0xff in the input, and the ASCII (American Standard
Code for Information Interchange) converter cannot convert that
into a Unicode character. This is because ASCII is a 7-bit character
set, i.e. it goes from 0..127. 0xFF is 255, so it is out of range.

Now, the line triggering this is

bz_file_out.wri te(line.encode( new_encode))

and it invokes *encode*, not *decode*. Why would it give a decode error
then?

Because:

decode: take a byte string, return a Unicode string
encode: take a Unicode string, take a byte string

So line should be a Unicode string, for .encode to be a meaningful thing
to do. Unfortunately, Python supports .encode also for byte strings.
If new_encode defines a character encoding, this does

class str:
def encode(self, encoding):
unistr = unicode(self)
return unistr.encode(e ncoding)

So it first tries to convert the current string into unicode, which
uses the system default encoding, which is us-ascii. Hence the error.

HTH,
Martin
--
http://mail.python.org/mailman/listinfo/python-list


Jul 18 '05 #9
Hi !

Try :

aa = u""
aa.encode("asci i","ignore")

Jul 18 '05 #10

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

Similar topics

13
9056
by: Randell D. | last post by:
Folks, I have two related questions: 1. I have seen unicode being mentioned in my javascript pocket book - is this the same as ascii codes? I think not though I'm not sure and I can't find any examples... 2. How do I read/set a string to an unprintable code? For example, how can I set the variable a to equal the equivalent of ascii code 7 or 8 or
1
1834
by: N | last post by:
Hi, I'm writing a small web service (using C#) which is going to receive a text file, add a line to it and send it back. Input is a string with each line ending with "\r\n". The problem is in the format of the output - looks like all ends of lines are missing, even if web service just receives and sends back the same string. Could it be some encoding issue?
19
3327
by: Thomas W | last post by:
I'm getting really annoyed with python in regards to unicode/ascii-encoding problems. The string below is the encoding of the norwegian word "fdselsdag". I stored the string as "fdselsdag" but somewhere in my code it got translated into the mess above and I cannot get the original string back. It cannot be printed in the console or written a plain text-file. I've tried to convert it using
1
3037
by: ronrsr | last post by:
I have an MySQL database called zingers. The structure is: zid - integer, key, autoincrement keyword - varchar citation - text quotation - text I am having trouble storing text, as typed in latter two fields. Special characters and punctuation all seem not to be stored and retrieved correctly.
6
5310
Robbie
by: Robbie | last post by:
Hi again all, here's something I'm stuck on... I'm making a function to convert a unicode character into the kind of code you need to put on a UTF-8 encoded web page (ampersand, hash, digits, semicolon). The program sees whether it's a unicode character by seeing if AscW(character)>255. It works fine most of the time, e.g. it converts this: original: 泳ぐ converted: &# 27891;&# 12368;
0
8686
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, well explore What is ONU, What Is Router, ONU & Routers main usage, and What is the difference between ONU and Router. Lets take a closer look ! Part I. Meaning of...
0
9173
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
9033
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
8911
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
8882
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...
1
6533
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupr who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4627
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2345
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2009
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.