1

私は次の機能を持っています

outFile = open("svm_light/{0}/predictions-average.txt".format(hashtag), "a")
with open('svm_light/{0}/predictions-{1}'.format(hashtag,segMent)) as f:
    tot_sum = 0
    for i,x in enumerate(f, 1):
        val = float(x)
        tot_sum += val            
        average = tot_sum/i
        outFile.write(average)  

各平均の出力を1行あたり1つの平均に出力しようとしているだけです。ただし、次のエラーが発生します...

  outFile.write(average)            
TypeError: expected a character buffer object

プログラムを次のように単純に変更すると、次のようになります。

with open('svm_light/{0}/predictions-{1}'.format(hashtag,segMent)) as f:
    tot_sum = 0
    for i,x in enumerate(f, 1):
         val = float(x)
         tot_sum += val            
         average = tot_sum/i
         print average

以下を出力します。

  @ubuntu:~/Documents/tweets/svm_light$ python2.7 tweetAverage2.py

  0.428908289104
  0.326446277105
  0.63672940322
  0.600035561829
  0.666699795857

出力を画面にきれいに出力しますが、実際の出力に表示されているのと同じように、1行あたり1つの平均を保存したいと思います。
Pythonは初めてで、ubuntuで2.7を使用しています。

アップデート

迅速な対応に感謝し、str 関数を導入しました。ただし、空のファイルが出力されます。ファイルの内容が少しの間表示された後、消えてしまいます。ほとんどの場合、ずっと上書きされています。だから私はこの印刷機能をどこかに置くべきではありませんでしたが、どこに?

4

1 に答える 1

3

averageファイルに書き込む前に文字列に変換する必要がありますstr()。そのためにまたは文字列フォーマットを使用できます。

outFile.write(str(average)) 

ヘルプfile.write:

>>> print file.write.__doc__
write(str) -> None.  Write string str to file.  #expects a string

Note that due to buffering, flush() or close() may be needed before
the file on disk reflects the data written.

アップデート:

outFile_name = "svm_light/{0}/predictions-average.txt".format(hashtag)
in_file_name = 'svm_light/{0}/predictions-{1}'.format(hashtag,segMent)
with open(in_file_name) as f, open(outFile_name, 'w') as outFile:
    tot_sum = 0
    for i,x in enumerate(f, 1):
        val = float(x)
        tot_sum += val            
        average = tot_sum/i
        outFile.write(average + '\n') # '\n' adds a new-line  
于 2013-06-07T17:50:00.637 に答える