2012-07-12 98 views
1

有没有人有这方面的经验?python sl4a unicode(Android)

我在过去的半年里一直在使用python 3.2,而我对2.6.2的记忆并不是那么好。

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' codec can't encode character u'\xf8' in position 3: ordinal not in range(128)

任何

在我的电脑下面的代码工作,使用2.6.1测试因为我需要输入它们以及从文件中读取文件?

+0

“但在电话上”? – 2012-07-12 16:11:58

+0

sl4a是Android设备的脚本层。 – beoliver 2012-07-12 16:16:16

回答

2

打印是一种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。这是打印机在目的地是终端时使用的内容。如果你确定你的python安装的所有用户(很可能只是你)比ascii更喜欢utf8,你可以改变你的python安装的默认编码。

  1. 找到你site.py:python -c 'import site; print site
  2. 打开它,找到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() 
    
  3. 更改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.

+0

太棒了。然后我在输入时使用解码? – beoliver 2012-07-12 16:19:28

+0

+1为跟进。非常感激。 – beoliver 2012-07-12 18:08:02

+0

您的codecs.open已经为您解码。如果你使用简单的'open()',你会得到字节,并且不用担心这个东西,但是如果你打算做任何类型的处理(例如将内容与另一个文件进行比较)你会想要获得角色,就像你使用'codecs.open'一样。 – bukzor 2012-07-13 15:20:32

0

打印功能需要将字符串转换为可打印格式,因为unicode字符串不能自动打印。使用repr print repr(i)包装将允许您打印,但您可能需要指定编码。