1

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!

4

2 に答える 2

4

上記のコメントで述べたように、に変更output_file.write(a)output_file.write(str(a))ます。あなたがprint何かをするとき、Pythonはあなたが印刷しているものすべての暗黙の文字列変換を行おうとします。printこれが、タプルを(ここで行っているように)実行することが機能する 理由です。file.write()暗黙の変換を行わないため、自分でそれを隠す必要がありますstr()

この回答へのコメントに記載されているように、おそらく.close()ファイルを呼び出す必要があります。

于 2012-06-07T13:55:46.640 に答える
0

次のようなコードを書くことができます:

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

開いたファイルに書き込む必要close()があります。そうしないと、ファイルを使用できません。

于 2012-06-07T17:33:05.263 に答える