2012-06-07 53 views
1

大家好,這是我試圖運行的代碼。我不是計算機科學家,我知道這是一個簡單的答案,我只是沒有工具來回答它。我試圖讓這個列表打印到一個文本文件。它可以工作,如果我打印到屏幕上。我得到的錯誤是這樣的:「類型錯誤:預期的字符緩衝區對象」python輸出數據類型混淆

這裏是代碼

input = open('Tyger.txt', 'r') 
text = input.read() 
wordlist = text.split() 

output_file = open ('FrequencyList.txt','w') 
wordfreq = [wordlist.count(p) for p in wordlist] 

#Pair words with corresponding frequency 

dictionary = dict(zip(wordlist,wordfreq)) 

#Sort by inverse Frequency and print 

aux = [(dictionary[key], key) for key in dictionary] 
aux.sort() 
aux.reverse() 

for a in aux: output_file.write(a) 

謝謝!

+0

這不會解決您的問題,但您應該考慮使用[with'語句](http://docs.python.org/reference/compound_stmts.html#the-with-statement)打開文件。您可能還想查看['collections.Counter'](http://docs.python.org/library/collections.html#collections.Counter)計算事物的位置,以及您在列表理解字典項目時[ (value,key)for dictionary.items()]' - using ['dict.items()'](http://docs.python.org/library/stdtypes.html#dict.items)意味着你不必一直在調用字典查找,這是更好閱讀。 –

+1

我會開始把'output_file.write(a)'改成'output_file.write(str(a))'。當您將其打印到屏幕上時,它會在打印之前進行隱式字符串轉換。寫入文件不會有這樣的事情。 –

+0

什麼是'type(a)'它應該是一個字符串。您可以使用'str(a)' – dm03514

回答

4

正如我在上面的評論中說的,將output_file.write(a)更改爲output_file.write(str(a))。當你的某個東西,Python試圖對你正在打印的任何東西進行隱式字符串轉換。這就是爲什麼print成爲一個元組(就像你在這裏做的那樣)。 file.write()沒有隱式轉換,所以你必須用str()自己轉換它。

正如在對此答案的評論中指出的那樣,您可能需要在文件上調用.close()

+0

sr2222這已糾正錯誤並且程序運行通過,但它不會在輸出文件中打印任何內容。我在做別的事嗎 –

+1

也許你應該 關閉() 該文件?像... output_file.close() – peixe

+0

也可以設置'sys.stdout = open('FrequencyList.txt','wt')'並使用'print'語句。如果你這樣做,你還需要保存和恢復'sys.stdout'的原始值。 – martineau

0

你可以寫你的代碼,如:

input = open('tyger.txt','r').read().split() 
...... 
......... 
............ 
for a in aux: 
    output_file.write(str(a)) 
    output_file.close() 

你必須close()你打開了寫一個文件,否則你將無法使用該文件。