2017-08-03 33 views
1

我正在制作一个算法来分类单词的次数,它们出现在由文件给出的文本中。Python:发布打印到文件特殊字符(西班牙文字母)

有我的方法:

def printToFile(self, fileName): 
    file_to_print = open(fileName, 'w') 
    file_to_print.write(str(self)) 
    file_to_print.close() 

且有STR:

def __str__(self): 
    cadena = "" 
    self.processedWords = collections.OrderedDict(sorted(self.processedWords.items())) 
    for key in self.processedWords: 
     cadena += str(key) + ": " + str(self.processedWords[key]) + "\n" 
    return cadena.decode('string_escape') 

当我通过控制台打印数据没有问题,不过,当我通过文件做随机出现字符。

This is should be the output to the file

This is the output given

+0

如果我这样做会发生这样的:“UnicodeEncodeError:'ascii'编解码器无法编码字符u'\ xc3'在位置22:序号不在范围内(128)“在”file_to_print.write(str(self) )“ – Alkesst

+0

重要的问题 - 你在什么版本? –

+0

我现在正在使用python 2.7 – Alkesst

回答

0

这看起来像一个编码问题,请尝试打开该文件是这样的: 打开( “文件名”, “W”,编码= “utf-8”) UTF8是最流行的编码,但它可能不是真正的编码,你可能必须检查其他编码,如utf16

+0

不行,不幸的是,OP忽略提及它们是在Python 2上, –

+0

我试过了,但它会把我抛出例外:“TypeError:'encoding'是该函数的一个无效关键字参数” – Alkesst

+0

@Alkesst,因为它只适用于Python 3.'codecs'模块中有类似的'open'函数,所以'import codecs'和uses ['codecs.open'](https://docs.python.org/2/library/codecs.html#codecs.open) –