作者blc (Anemos)
看板Python
標題Re: [問題] unicode裡有str資料該怎麼轉?
時間Thu Feb 4 11:43:08 2016
只好用try解決了……
def try_to_unicode(text):
encs = ['iso-8859-1','iso-8859-2'] ## 可以任意增加編碼
#print("try: "+repr(text))
for i in encs:
try:
t = text.encode(i).decode('utf-8')
except UnicodeEncodeError:
continue
#print(" "+i+" is right code")
return t
return text
如果有更好的方法也請指教一下。
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 140.109.254.74
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1454557391.A.169.html
→ buganini: 你的json長什麼樣子啊? 用json.loads沒遇過問題的說 02/04 22:49
→ buganini: 我猜你的資料在塞給json.loads之前就被錯誤地decode過了 02/04 22:52
→ buganini: json理論上只能裝utf-8,不會扯上其他iso-8859-* 02/04 22:53
→ buganini: 可能是json str被當作iso-8859-* decode成unicode 02/04 22:56
→ buganini: 再丟給json.loads,就跑出這樣的結果 02/04 22:56