How to handle Unicode (non-ASCII) characters in Python?(如何在 Python 中处理 Unicode(非 ASCII)字符?)
问题描述
我正在使用 Python 进行编程,我正在从网页通过 urllib2 库.问题是该页面可以为我提供非 ASCII 字符,例如 'ñ'、'á' 等.就在 urllib2code> 得到这个字符,它会引发一个异常,像这样:
I'm programming in Python and I'm obtaining information from a web page through the urllib2 library. The problem is that that page can provide me with non-ASCII characters, like 'ñ', 'á', etc. In the very moment urllib2 gets this character, it provokes an exception, like this:
File "c:Python25libhttplib.py", line 711, in send
self.sock.sendall(str)
File "<string>", line 1, in sendall:
UnicodeEncodeError: 'ascii' codec can't encode character u'xf1' in position 74: ordinal not in range(128)
我需要处理这些字符.我的意思是,我不想处理异常而是继续程序.有没有什么办法,例如(我不知道这是否是愚蠢的),使用另一个 codec 而不是 ASCII?因为我必须处理这些字符,将它们插入数据库等.
I need to handle those characters. I mean, I don't want to handle the exception but to continue the program. Is there any way to, for example (I don't know if this is something stupid), use another codec rather than the ASCII? Because I have to work with those characters, insert them in a database, etc.
推荐答案
您只需从套接字读取一组字节.如果你想要一个字符串,你必须解码它:
You just read a set of bytes from the socket. If you want a string you have to decode it:
yourstring = receivedbytes.decode("utf-8")
(用您使用的任何编码替换 utf-8)
(substituting whatever encoding you're using for utf-8)
然后你必须做相反的事情才能将它发回:
Then you have to do the reverse to send it back out:
outbytes = yourstring.encode("utf-8")
这篇关于如何在 Python 中处理 Unicode(非 ASCII)字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 Python 中处理 Unicode(非 ASCII)字符?
基础教程推荐
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
