有没有人有这方面的经验?
最近半年一直在用python 3.2,对2.6.2的内存力不是很好。
在我的电脑上,以下代码有效,使用 2.6.1 测试:
import contextlib
import codecs
def readfile(path):
with contextlib.closing( codecs.open( path, 'r', 'utf-8' )) as f:
for line in f:
yield line
path = '/path/to/norsk/verbs.txt'
for i in readfile(path):
print i
但在手机上它到达第一个特殊字符 ø
并抛出:
UnicodeEncodeError: 'ascii' 编解码器无法对位置 3 中的字符 u'\xf8' 进行编码:序号不在范围内 (128)
我需要输入它们以及从文件中读取任何想法吗?
最佳答案
打印是一种 I/O 操作。 I/O 需要字节。您在 i
中拥有的是 unicode,或字符。当我们谈论 ascii 时,字符只会直接转换为字节,但在您的手机上遇到了非 ascii 字符 ( u'\xf8' is ø )。要将字符转换为字节,您需要对其进行编码。
import contextlib
import codecs
def readfile(path):
with contextlib.closing( codecs.open( path, 'r', 'utf-8' )) as f:
for line in f:
yield line
path = '/path/to/norsk/verbs.txt'
for i in readfile(path):
print i.encode('utf8')
至于为什么这适用于您的代码在一台机器上运行而不在另一台机器上运行,我敢打赌 python 的自动检测在这些情况下发现了不同的东西。在每台设备上运行:
$ python
>>> import sys
>>> sys.getfilesystemencoding()
'UTF-8'
我希望您会在一个上看到 utf8,在另一个上看到 ascii。这是当目的地是终端时 print 使用的内容。如果您确定您的 python 安装的所有用户(很可能只有您)更喜欢 utf8 而不是 ascii,您可以更改 python 安装的默认编码。
- 找到你的站点.py:
python -c 'import site;打印站点
打开它,找到setencoding函数:
def setencoding(): """Set the string encoding used by the Unicode implementation. The default is 'ascii', but if you're willing to experiment, you can change this.""" encoding = "ascii" # Default value set by _PyUnicode_Init()
将
encoding = "ascii"
行更改为encoding = "UTF-8"
享受工作带来的乐趣。您可以在此处找到有关此主题的更多信息:http://blog.ianbicking.org/illusive-setdefaultencoding.html
如果您更喜欢字节与字符的严格分离,例如 python3 提供的,您可以设置 encoding = "undefined"
。 undefined
编解码器将“Raise an exception for all conversions. Can be used as the system encoding if no automatic coercion between byte and Unicode strings is desired.”
关于android - python sl4a unicode (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11455951/