2017-08-03 65 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) –