programing

python 3.2 UnicodeError: 'charmap' 코덱은 9629 위치의 '\u2013' 문자를 인코딩할 수 없습니다: 다음 위치의 문자 맵

easyjava 2023. 6. 8. 22:40
반응형

python 3.2 UnicodeError: 'charmap' 코덱은 9629 위치의 '\u2013' 문자를 인코딩할 수 없습니다: 다음 위치의 문자 맵

sqlite3 데이터베이스에서 데이터를 빼내는 스크립트를 만들려고 하는데 문제가 생겼습니다.

데이터베이스의 필드는 텍스트 형식이며, 에는 HTML 형식의 텍스트가 포함되어 있습니다.아래 텍스트 참조

<html>
<head>
<title>Yahoo!</title>
</head>
<body>
<style type="text/css">
html {}
.yshortcuts {border-bottom:none !important;}
.ReadMsgBody {width:100%;}
.ExternalClass{width:100%;}
</style>
<table cellpadding="0" cellspacing="0" bgcolor="#ffffff">    
<tr>
<td width="550" valign="top" align="left">

    <table cellpadding="0" cellspacing="0" width="500">
        <tr>
            <td colspan="3"><img        src="http://mail.yimg.com/nq/assets/sharedmessages/v1/us/logo.gif" width="292" height="51" style="display:block;" border="0" alt="Yahoo! Mail"></td>
        </tr>
        <tr>
            <td rowspan="3" width="1" bgcolor="#c7c4ca"></td>
            <td width="498" height="1" bgcolor="#c7c4ca"></td>
            <td rowspan="3" width="1" bgcolor="#c7c4ca"></td>
        </tr>
        <tr>
            <td width="498" valign="top" align="left">
            <table cellpadding="0" cellspacing="0">
                <tr>
                    <td width="498" bgcolor="#61399d" align="left" valign="top">
                    <table cellspacing="0" cellpadding="0"><tr><td height="24"></td></tr></table>
                    <div style="font-family:Arial, Helvetica, sans-serif;font-size:23px;line-height:27px;margin-bottom:10px;color:#ffffff;margin-left:15px;"><span style="color:#ffffff;text-decoration:none;font-weight:bold;line-height:27px;">Välkommen till Yahoo! Mail.</span></div>
                    <div style="font-family:Arial, Helvetica, sans-serif;font-size:22px;line-height:26px;margin-bottom:1px;color:#ffffff;margin-left:15px;margin-bottom:7px;margin-right:15px;">Ansluta och dela går snabbt och enkelt och är tillgängligt överallt.</div>
                    </td>
                </tr>
                <tr>
                    <td><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/b1.gif" width="498" height="18" style="display:block;" border="0"></td>
                </tr>
            </table>
            <table cellpadding="0" cellspacing="0" width="498">
                <tr>
                    <td width="292" valign="top">
                    <table cellpadding="0" cellspacing="0">
                        <tr>
                            <td><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/grad.gif" width="292" height="9" style="display:block;"></td>
                        </tr>
                        <tr>
                            <td width="292" bgcolor="#ffffff" align="left" valign="top">
                            <table cellspacing="0" cellpadding="0"><tr><td height="11"></td></tr></table>
                            <div style="margin-left:15px;">                  
                                <div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:18px;color:#333333;margin-bottom:11px;font-weight:bold;">Det är lätt som en plätt att komma igång.</div>
                                <table cellpadding="0" cellspacing="0" width="267">
                                    <tr>
                                        <td width="16" align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:16px;color:#61399d;margin-bottom:9px;font-weight:bold;">1. </div></td>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#61399d;margin-bottom:9px;"><a rel="nofollow" target="_blank" href="http://us-mg999.mail.yahoo.com/neo/launch?action=contacts" style="text-decoration:underline;color:#61399d;"><span>Lägg till alla dina kontakter på en plats</span></a>.</div></td>
                                    </tr>
                                    <tr>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:16px;color:#61399d;margin-bottom:9px;font-weight:bold;">2. </div></td>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#61399d;margin-bottom:9px;"><a rel="nofollow" target="_blank" href="http://mrd.mail.yahoo.com/themes" style="text-decoration:underline;color:#61399d;"><span>Anpassa din nya inkorg</span></a>.</div></td>
                                    </tr>
                                    <tr>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:14px;line-height:16px;color:#61399d;margin-bottom:9px;font-weight:bold;">3. </div></td>
                                        <td align="left" valign="top"><div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#61399d;"><a rel="nofollow" target="_blank" href="http://se.overview.mail.yahoo.com/mobile" style="text-decoration:underline;color:#61399d;"><span>Anslut överallt på dina mobila enheter</span></a>.</div></td>
                                    </tr>
                                </table>

                            </div>
                            </td>
                        </tr>
                        <tr><td height="13"></td></tr>
                    </table>
                    </td>
                    <td width="196" valign="top">
                    <table cellpadding="0" cellspacing="0">
                        <tr>
                            <td width="1" bgcolor="#fbfbfd" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g1.gif" width="1" height="21" style="display:block;"></td>
                            <td width="1" bgcolor="#f5f6fa" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g2.gif" width="1" height="21" style="display:block;"></td>
                            <td width="1" bgcolor="#e8eaf1" valign="top"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/g3.gif" width="1" height="21" style="display:block;"></td>
                            <td width="1" bgcolor="#d4d4d4"></td>
                            <td width="186" bgcolor="#f0f0f0" align="left" valign="top">  
                            <table cellspacing="0" cellpadding="0"><tr><td height="3">   </td></tr></table>
                            <div style="margin-left:11px;">
                            <div style="font-family:Arial, Helvetica, sans-serif;font-size:13px;line-height:16px;color:#333333;margin-bottom:9px;"><b>Info för dig:</b></div>
                            <div style="font-family:Arial, Helvetica, sans-serif;font-size:12px;color:#43494e;line-height:18px;margin-bottom:10px;">
                            Yahoo!-ID och e-postadress:<br />
                            <div style="font-family:Arial, Helvetica, sans-serif;font-size:12px;color:#43494e;line-height:18px;">
                            Håll ditt konto och inställningar aktuella. <br><a rel="nofollow" target="_blank" href="https://edit.yahoo.com/config/eval_profile" style="text-decoration:underline;color:#61399d;"><span>Mitt konto</span></a> 
                            </div>
                            </div>
                            <table cellspacing="0" cellpadding="0"><tr><td height="20"></td></tr></table>
                            </td>
                            <td width="1" bgcolor="#dbdbdb"></td>
                            <td width="1" bgcolor="#ced2de"></td>
                            <td width="1" bgcolor="#dbdfed"></td>
                            <td width="1" bgcolor="#e8ebf3"></td>
                            <td width="1" bgcolor="#f3f4f9"></td>
                            <td width="1" bgcolor="#fafbfc"></td>
                        </tr>
                        <tr>
                            <td colspan="11"><img src="http://mail.yimg.com/nq/assets/sharedmessages/v1/all/b2.gif" width="196" height="8" style="display:block;" border="0"></td>
                        </tr>
                        <tr><td height="13"></td></tr>
                    </table>
                    </td>
                    <td width="10"></td>
                </tr>
            </table>
            </td>
        </tr>
        <tr>
            <td width="498" height="1" bgcolor="#c7c4ca"></td>
        </tr>
    </table>
    <table cellpadding="0" cellspacing="0" width="500">
        <tr>
            <td align="center" valign="top">
            <table cellspacing="0" cellpadding="0"><tr><td height="10"></td></tr></table>
                <div style="font-family:Arial, Helvetica, sans-serif;font-size:11px;line-height:18px;margin-bottom:10px;">
                <a rel="nofollow" target="_blank" href="http://info.yahoo.com/legal/se/yahoo/utos.html" style="text-decoration:underline;color:#61399d;">Yahoo! Villkor för användning</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a rel="nofollow" target="_blank" href="http://info.yahoo.com/legal/se/yahoo/mail/atos.html" style="text-decoration:underline;color:#61399d;">Yahoo! Mail –Villkor för användning</a>&nbsp;&nbsp;&nbsp;|&nbsp;&nbsp;&nbsp;<a rel="nofollow" target="_blank" href="http://info.yahoo.com/privacy/se/yahoo/details.html" style="text-decoration:underline;color:#61399d;">Yahoo! Sekretesspolicy</a>
                </div>
            </td>
        </tr>
        <tr>
            <td align="left" valign="top">
                <div style="font-family:Arial, Helvetica, sans-serif;font-size:11px;line-height:14px;color:#545454;margin-left:16px;margin-right:14px;">Var god svara inte på detta meddelande. Detta är ett servicemeddelande som rör din användning av Yahoo! Mail. Om du vill veta mer om Yahoo!s användning av personlig information, inklusive användning av webb-beacons i HTML-baserad e-post, kan du läsa vår Yahoo! Sekretesspolicy. Yahoo!s adress är 701 First Avenue, Sunnyvale, CA 94089, USA.<br /><br />RefID: lp-1037111</div>
            </td>
        </tr>
    </table>





    </td>
</tr>
</table>
<img width="1" height="1" src="http://pclick.internal.yahoo.com/p/s=2143684696">
</body>
</html>`

그리고 데이터를 추출하려는 파이썬 코드는 다음과 같습니다.

>>> import sqlite3
>>> conn = sqlite3.connect('C:/temp/Mobils/export/com.yahoo.mobile.client.android.mail/databases/mail.db')
>>> c = conn.cursor()
>>> conn.row_factory=sqlite3.Row
>>> c.execute('select body from messages_1 where _id=7')
<sqlite3.Cursor object at 0x0000000001FB78F0>
>>> r = c.fetchone()
>>> r.keys()
['body']
>>> print(r['body'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
    return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>
>>>

이것을 파일에 인쇄/쓰기하는 방법에 대해 아는 사람이 있습니까?예, 이것이 stdout으로 인쇄된다는 것을 알고 있지만 파일에 쓰려고 하면 동일한 Unicode EncodeError가 발생합니다.나는 파일 객체의 쓰기 방법을 모두 시도했습니다.print(r['body'], file=f).

쓸 파일을 열 때 모든 문자를 처리할 수 있는 특정 인코딩으로 파일을 엽니다.

with open('filename', 'w', encoding='utf-8') as f:
    print(r['body'], file=f)

답장이 조금 늦었을 수도 있습니다.저는 오늘 우연히 같은 문제에 부딪혔습니다.Windows에서 콘솔 인코더를 다음으로 변경할 수 있습니다.utf-8또는 데이터를 나타낼 수 있는 다른 인코더.그러면 다음으로 인쇄할 수 있습니다.sys.stdout.

먼저 콘솔에서 다음 코드를 실행합니다.

chcp 65001
set PYTHONIOENCODING=utf-8

그러면 시작.python당신이 원하는 것은 무엇이든 하세요.

Python 3은 유니코드를 처리하지만 내부에서 실행 중인 Windows 콘솔이나 POSIXtty는 처리하지 않습니다.그래서, 당신이 언제든지.print또는 유니코드 문자열을 다음 주소로 보냅니다.stdout콘솔/tty에 연결되어 있으므로 Python은 이를 인코딩해야 합니다.

오류 메시지는 Python이 사용하려고 했던 문자 집합을 간접적으로 알려줍니다.

  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode

이는 문자 집합이 다음과 같다는 것을 의미합니다.cp850.

이 문자 집합에 적합한 문자가 없는지 테스트할 수 있습니다.'\u2013'.encode('cp850')또는 온라인에서 cp850을 검색할 수 있습니다(예: 위키백과).

Python이 추측을 잘못했을 수 있으며, 콘솔이 UTF-8로 설정되어 있다고 가정합니다. (이 경우 수동으로 설정하기만 하면 됩니다.)sys.stdout.encoding='utf-8'.) 또한 콘솔을 UTF-8로 설정하려고 했으나 잘못된 작업을 수행했을 수 있습니다. (그런 경우 superuser.com 에서 후속 조치를 취하고 싶을 수도 있습니다.)

하지만 아무 문제가 없다면, 그 캐릭터를 인쇄할 수 없습니다.엄격하지 않은 오류 처리기 중 하나를 사용하여 수동으로 인코딩해야 합니다.예:

>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'

그러면 콘솔에 인쇄되지 않는 문자열을 어떻게 인쇄할 수 있을까요?

다음을 모두 교체할 수 있습니다.print다음과 같은 기능을 사용합니다.

>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?

하지만 그것은 꽤 빨리 지루해질 것 같아요.

입니다.sys.stdout:

>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?

파일로 인쇄하는 경우 설정할 필요가 없다는 점을 제외하고는 거의 동일합니다.f.errors사실 이후에, 당신은 건설 시간에 그것을 설정할 수 있습니다.다음과 같이 입력합니다.

with open('path', 'w', encoding='cp850') as f:

수행할 작업:

with open('path', 'w', encoding='cp850', errors='replace') as f:

물론 UTF-8 파일을 사용할 수 있다면 마크 랜섬의 대답에서 알 수 있듯이 그렇게 하십시오.

with open('path', 'w', encoding='utf-8') as f:

사용하는 나를 위해export PYTHONIOENCODING=UTF-8worked . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ?

Windows(gitbash)의 경우:

chcp.com 65001
export PYTHONIOENCODING=utf-8

그런 다음 스크립트를 실행할 수 있습니다. 제 경우에는 플라스크였습니다. 그래서 마침내 mysql db에서 웹사이트의 utf를 디코딩할 수 있었습니다.

언급URL : https://stackoverflow.com/questions/16346914/python-3-2-unicodeencodeerror-charmap-codec-cant-encode-character-u2013-i

반응형