Python: codecs.open 引发 UnicodeEncodeError
我正在尝试使用 orgnode.py(从这里获取)来解析 org 文件。这些文件是英文和波斯文的,使用 file -i
命令检查后,发现它们是 utf-8 编码的。但是,当我使用 makelist 函数(这个函数内部使用了 codec.open 并指定 utf-8 编码)时,出现了一个错误:
>>> Orgnode.makelist("toread.org")
[** [[http://www.apa.org/helpcenter/sexual-orientation.aspx][Sexual orientation, homosexuality and bisexuality]] :ToRead:
Added:[2013-11-06 Wed]
, ** [[http://stackoverflow.com/questions/11384516/how-to-make-all-org-files-under-a-folder-added-in-agenda-list-automatically][emacs - How to make all org-files under a folder added in agenda-list automatically? - Stack Overflow]]
(setq org-agenda-text-search-extra-files '(agenda-archives "~/org/subdir/textfile1.txt" "~/org/subdir/textfile1.txt"))
Added:[2013-07-23 Tue]
, Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 63-66: ordinal not in range(128)
这个函数会返回一个 org 头部的列表,但最后一项(是用波斯文写的)却显示了错误信息。有没有什么建议可以解决这个错误?
1 个回答
根据错误信息,问题出在你在Python控制台输入的那行代码上(Orgnode.makelist("toread.org")
),而不是在执行这行代码时调用的某个函数里。
这种情况通常是因为编码错误,解释器在自动将这行代码的返回值转换成可以在控制台显示的格式时出现了问题。显示的文本是通过内置的repr()
函数处理返回值后得到的。
这里,makelist
的返回值是一个unicode
对象,而解释器默认尝试用"ascii"
编码将其转换为str
类型。
问题的根源在于Orgnode.__repr__
方法(https://github.com/albins/orgnode/blob/master/Orgnode.py#L592),它返回了一个unicode
对象(因为节点内容已经通过codecs.open
自动解码),而通常__repr__
方法应该返回只包含安全(ASCII)字符的字符串。
你可以对Orgnode做一个最小的修改来解决这个问题:
-- a/Orgnode.py
+++ b/Orgnode.py
@@ -612,4 +612,4 @@ class Orgnode(object):
# following will output the text used to construct the object
n = n + "\n" + self.body
- return n
+ return n.encode('utf-8')
如果你想要一个只返回ASCII字符的版本,可以使用'string-escape'
作为编码,而不是'utf-8'
。
这只是一个快速且简单的解决办法。真正的解决方案应该是重新编写一个合适的__repr__
方法,并且添加这个类缺少的__str__
和__unicode__
方法。(如果我有时间,我可能会自己修复这个问题,因为我对用Python代码处理我的Org-mode文件很感兴趣)