作者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://webptt.com/cn.aspx?n=bbs/Python/M.1454557391.A.169.html
1F:→ buganini: 你的json长什麽样子啊? 用json.loads没遇过问题的说 02/04 22:49
2F:→ buganini: 我猜你的资料在塞给json.loads之前就被错误地decode过了 02/04 22:52
3F:→ buganini: json理论上只能装utf-8,不会扯上其他iso-8859-* 02/04 22:53
4F:→ buganini: 可能是json str被当作iso-8859-* decode成unicode 02/04 22:56
5F:→ buganini: 再丢给json.loads,就跑出这样的结果 02/04 22:56