[問題] 中文字內容的utf-8編碼xml檔之處理

看板Python作者 (要運動)時間4月前 (2023/12/08 23:20), 4月前編輯推噓0(005)
留言5則, 2人參與, 4月前最新討論串1/2 (看更多)
各位大大 晚安 有一個cd_catalog.xml檔案(以utf-8編碼)如下 <CATALOG> <CD> <ARTIST>&#x5468;&#x6770;&#x502b</ARTIST> </CD> </CATALOG> 上面是某設備的輸出檔案cd_catalog.xml(以utf-8編碼) 以Windows 10的筆記本notepad打開,看到是上面unicode編碼方式 我不知道第一個字元&#x5468,為何不是\u5468的unicode編碼表示方式? 上面unicode編碼處是下面的"周杰倫" <CATALOG> <CD> <ARTIST>周杰倫</ARTIST> </CD> </CATALOG> 有讀過python的xml處理的書 也問過bing copilot(chatGPT) 還是不了解用筆記本打開cd_catalog.xml是上面第一種編碼方式,如何用python程式碼 Windows notepad打開可轉成上面第二種中文字顯示的unicode檔 decoded_string = bytes(unicode_string, "utf-8").decode("unicode_escape") 除此之外,上面程式碼也不了解 再請各位大大指引方向,我再去看相關資料 謝謝大大 ----------------------------------------------------------------------- 補充下面Python執行結果: s=u'中文字串' print(type(s)) <class 'str'> print(s.encode('utf8')) b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe4\xb8\xb2' print(s.encode('utf8').decode('utf8')) 中文字串 s2='中文字串' print(type(s2)) <class 'str'> print(s2.encode('utf8')) b'\xe4\xb8\xad\xe6\x96\x87\xe5\xad\x97\xe4\xb8\xb2' print(s2.encode('utf8').decode('utf8')) 中文字串 ----------------------------------------------------------------------- 最後遭遇問題是,上面是unicode string '中文字串'的'中'轉成\xe4\xb8\xad 但'中'的xml unicode是&#xe4b8 之類的 不曉得有無xml encode()函數,可進行上面的轉換?? -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 36.230.92.107 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1702048816.A.DCB.html

12/08 23:36, 4月前 , 1F
那就是xml unicode的寫法啊
12/08 23:36, 1F

12/09 11:06, 4月前 , 2F
謝謝1F大大的指教
12/09 11:06, 2F
※ 編輯: kino818 (36.230.92.107 臺灣), 12/09/2023 11:34:07

12/09 15:23, 4月前 , 3F
已解決問題,str.encode('utf-8')可將來源編碼成xml uni
12/09 15:23, 3F

12/09 15:23, 4月前 , 4F
code編碼,例如&#x9999;,再多接.decoce('utf-8')可讓筆
12/09 15:23, 4F

12/09 15:23, 4月前 , 5F
記本看到中文字
12/09 15:23, 5F
文章代碼(AID): #1bSpGmtB (Python)
文章代碼(AID): #1bSpGmtB (Python)