我正在尝试使用orgnode.py (从这里开始)来解析组织文件。这些文件是英语/波斯语,使用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)函数返回一个组织标题列表,但它没有返回最后一项(用波斯语编写),而是显示了错误。有什么建议吗?我怎么处理这个错误?
发布于 2014-03-25 13:15:30
正如跟踪所告诉您的,异常是由您在Python本身(Orgnode.makelist("toread.org"))上输入的语句引发的,而不是在语句的计算期间调用的函数中。
当解释器自动转换语句的返回值以将其显示在控制台上时,这是典型的编码错误。显示的文本是将repr()内置的内容应用于返回值的结果。
在这里,repr()的makelist结果是一个unicode对象,解释器试图使用默认的"ascii"编解码器将其转换为str。
罪魁祸首是Orgnode.__repr__方法(https://github.com/albins/orgnode/blob/master/Orgnode.py#L592),它返回unicode对象(因为节点内容已被codecs.open自动解码),尽管通常期望__repr__方法返回只有安全字符的字符串。
下面是您可以对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代码操作我的操作模式文件很感兴趣)
https://stackoverflow.com/questions/22617737
复制相似问题