Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7738405
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 1, 20262026-06-01T08:15:20+00:00 2026-06-01T08:15:20+00:00

I have a file which is mostly UTF-8, but some Windows-1252 characters have also

  • 0

I have a file which is mostly UTF-8, but some Windows-1252 characters have also found their way in.

I created a table to map from the Windows-1252 (cp1252) characters to their Unicode counterparts, and would like to use it to fix the mis-encoded characters, e.g.

cp1252_to_unicode = {
    "\x85": u'\u2026', # …
    "\x91": u'\u2018', # ‘
    "\x92": u'\u2019', # ’
    "\x93": u'\u201c', # “
    "\x94": u'\u201d', # ”
    "\x97": u'\u2014'  # —
}

for l in open('file.txt'):
    for c, u in cp1252_to_unicode.items():
        l = l.replace(c, u)

But attempting to do the replace this way results in a UnicodeDecodeError being raised, e.g.:

"\x85".replace("\x85", u'\u2026')
UnicodeDecodeError: 'ascii' codec can't decode byte 0x85 in position 0: ordinal not in range(128)

Any ideas for how to deal with this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-01T08:15:22+00:00Added an answer on June 1, 2026 at 8:15 am

    If you try to decode this string as utf-8, as you already know, you will get an “UnicodeDecode” error, as these spurious cp1252 characters are invalid utf-8 –

    However, Python codecs allow you to register a callback to handle encoding/decoding errors, with the codecs.register_error function – it gets the UnicodeDecodeerror a a parameter – you can write such a handler that atempts to decode the data as “cp1252”, and continues the decoding in utf-8 for the rest of the string.

    In my utf-8 terminal, I can build a mixed incorrect string like this:

    >>> a = u"maçã ".encode("utf-8") + u"maçã ".encode("cp1252")
    >>> print a
    maçã ma�� 
    >>> a.decode("utf-8")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python2.6/encodings/utf_8.py", line 16, in decode
        return codecs.utf_8_decode(input, errors, True)
    UnicodeDecodeError: 'utf8' codec can't decode bytes in position 9-11: invalid data
    

    I wrote the said callback function here, and found a catch: even if you increment the position from which to decode the string by 1, so that it would start on the next chratcer, if the next character is also not utf-8 and out of range(128), the error is raised at the first out of range(128) character – that means, the decoding “walks back” if consecutive non-ascii, non-utf-8 chars are found.

    The worka round this is to have a state variable in the error_handler which detects this “walking back” and resume decoding from the last call to it – on this short example, I implemented it as a global variable – (it will have to be manually reset to “-1” before each call to the decoder):

    import codecs
    
    last_position = -1
    
    def mixed_decoder(unicode_error):
        global last_position
        string = unicode_error[1]
        position = unicode_error.start
        if position <= last_position:
            position = last_position + 1
        last_position = position
        new_char = string[position].decode("cp1252")
        #new_char = u"_"
        return new_char, position + 1
    
    codecs.register_error("mixed", mixed_decoder)
    

    And on the console:

    >>> a = u"maçã ".encode("utf-8") + u"maçã ".encode("cp1252")
    >>> last_position = -1
    >>> print a.decode("utf-8", "mixed")
    maçã maçã 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have multi-lingual TeX document mostly in Russian but I also include some terms
I have a file which is an XML representation of some data that is
i have a file which contains a lot of update query and some other
I have a file which may be in ASCII or UTF-8 format. I can
I have a file which contains mostly of names mapping to a certain list
I have a file which has multiple columns, whitespace separated. e.g: data1 data2 data3
I have .zip file which contain csv data. I am reading .zip file using
I have this file which I need to read the first bytes to check
I have a file which is combination of PHP and HTML. How can i
I have a file which i'm parsing out myself. Every time i spot a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.