大家好,這是我試圖運行的代碼。我不是計算機科學家,我知道這是一個簡單的答案,我只是沒有工具來回答它。我試圖讓這個列表打印到一個文本文件。它可以工作,如果我打印到屏幕上。我得到的錯誤是這樣的:「類型錯誤:預期的字符緩衝區對象」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)
謝謝!
這不會解決您的問題,但您應該考慮使用[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)意味着你不必一直在調用字典查找,這是更好閱讀。 –
我會開始把'output_file.write(a)'改成'output_file.write(str(a))'。當您將其打印到屏幕上時,它會在打印之前進行隱式字符串轉換。寫入文件不會有這樣的事情。 –
什麼是'type(a)'它應該是一個字符串。您可以使用'str(a)' – dm03514