问题描述
||
在Mac上的Python 2.7中,我正在打印使用nltk的PlaintextCorpusReader检索的文件名:
infobasecorpus = PlaintextCorpusReader(corpus_root,\'.*\\.txt\')
for fileid in infobasecorpus.fileids():
print fileid
并由于文件名中的“ 2”符号而获得“ 1”。
据我了解,“ 3”是一个unicode字符串,在打印之前我需要将其编码为默认编码,并且默认编码为ASCII。
如果我使用print fileid.encode(\'ascii\',\'ignore\')
,则会出现相同的错误。
如果我通过在site.py
中设置encoding = \"utf-8\"
来更改默认编码,则(根据此建议)它可以工作。
谁能告诉我:
(a)为什么“ 7”失败了
(b)为什么“ 8”起作用,并且
(c)如果我在这里做错了怎么办? (例如,这描述了将默认编码设置为\'ug hack \',这会导致字符串的滥用和错误代码的创建。)
(免责声明:Python的新手,如果这很明显,感谢您的耐心配合)
==========================================
更新以回应Rob:
Rob,这是测试代码的全文:
import sys
import os
from nltk.corpus import PlaintextCorpusReader
corpus_root = \'/Users/richlyon/Documents/Filing/Infobase/\'
infobasecorpus = PlaintextCorpusReader(corpus_root,\'.*\\.txt\')
for fileid in infobasecorpus.fileids():
print type(fileid) # result <type \'str\'>
fileid = fileid.decode(\'utf8\')
print type(fileid) # result <type \'unicode\'>
print fileid.encode(\'ascii\')
我将默认编码设置回了ascii
并运行它。
在文件名中的“ 2”上,“ 11”仍然失败。
==========================================
最后更新,以防对其他人有帮助。
我需要写:
fileid = fileid.decode(\'utf8\')
print fileid.encode(\'ascii\',\'ignore\')
但是如果将“ 15”字符串送入,则会导致“ 14”阻塞,这似乎与在进一步处理之前立即将所有内容转换为unicode的建议相矛盾。
但是现在可以了。谢谢大家,特别是Rob。
解决方法
检查fileid对象的类型。我怀疑它不是您建议的unicode对象。之所以会提出ѭ16raised,是因为在python对输出字符串进行编码之前(由
print
进行了隐式解码)。
字符串成功解码(转换为unicode)后,您就可以通过使用终端支持的编解码器对其进行显式编码来进行打印。如果您的终端支持unicode的显示,则在输出之前可能不需要对其进行编码。
infobasecorpus = PlaintextCorpusReader(corpus_root,\'.*\\.txt\')
for fileid in infobasecorpus.fileids():
fileid = fileid.decode(\'utf8\') ## fileid is now a unicode object
print fileid.encode(\'utf8\')
用文件系统使用的任何编码替换“ 19”(不确定Windows上是否为latin1?)。
编辑:覆盖整个站点范围的默认编码被认为是一种黑客,因为它a)可以隐藏编程问题,这可能意味着您的代码无法跨python安装进行移植,并且b)它可能影响从同一python安装运行的其他代码。此外,明确地编码和解码字符串可以使您以后返回代码时的工作变得更加轻松。您不必记住您修改了site.py