Reputation: 1395
Hi all this is the code I am trying to run. I am not a computer scientist and I know this is an easy answer I just do not have the tools to answer it. I am trying to get this list printed to a text file. It works if I print to screen. The error I get is this: "TypeError: expected a character buffer object"
here is the code
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)
Thanks!
Upvotes: 1
Views: 352
Reputation: 143
you can write your code like:
input = open('tyger.txt','r').read().split()
......
.........
............
for a in aux:
output_file.write(str(a))
output_file.close()
you must close()
a file what you have opened to write,otherwise you won't be able to use the file.
Upvotes: 0
Reputation: 26160
As I said in the comments above, change output_file.write(a)
to output_file.write(str(a))
. When you print
something, Python attempts to do an implicit string conversion of whatever you are printing. That is why print
ing a tuple (as you are doing here) works. file.write()
does no implicit conversion, so you have to covert it yourself with str()
.
As noted in the comments to this answer, you probably need to call .close()
on the file.
Upvotes: 4