1

私のスクリプトでは、テキスト ファイルごとに特定の機能を計算します。次に、結果を CSV ファイルに書き込みます。ただし、それらをリストに入れることができないようです。文字列になってしまいます。機能の計算を省略し、CSV ファイルへの書き込みに使用するコードを投稿しているだけです。私は初心者です :)

fnew = open('results.csv', 'w+')
fnew.write('fileid,feature,resultaat\n')

……特徴を計算します。

    fnew.write(cat+','+sentstr+',perplexity    (bigram),'+str(lmbi.perplexity(sent))+'\n')
    fnew.write(cat+','+sentstr+',perplexity (trigram),'+str(lmtr.perplexity(sent))+'\n')
    fnew.write(cat+','+sentstr+',word_senses,'+str(aver_senses)+'\n')
    fnew.write(cat+','+sentstr+',polarity,'+str(polarity(sent))+'\n')
    fnew.write(cat+','+sentstr+',modality,'+str(modality(Sentence(parse(joined, chunks=False, lemmata=True))))+'\n')
    fnew.write(cat+','+sentstr+',subjectivity,'+str(subjectivity(sent))+'\n')

fnew.close()
4

2 に答える 2

0

Python のデータ構造をファイルに保存したい場合は、pickleを検討してください。

import pickle

data1 = {'a': [1, 2.0, 3, 4+6j],
         'b': ('string', u'Unicode string'),
         'c': None}

selfref_list = [1, 2, 3]
selfref_list.append(selfref_list)

output = open('data.pkl', 'wb')

# Pickle dictionary using protocol 0.
pickle.dump(data1, output)

# Pickle the list using the highest protocol available.
pickle.dump(selfref_list, output, -1)

output.close()

または棚上げ

import shelve

d = shelve.open(filename) # open -- file may get suffix added by low-level
                          # library

d[key] = data   # store data at key (overwrites old data if
                # using an existing key)
data = d[key]   # retrieve a COPY of data at key (raise KeyError if no
                # such key)
del d[key]      # delete data stored at key (raises KeyError
                # if no such key)
flag = d.has_key(key)   # true if the key exists
klist = d.keys() # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = range(4)  # this works as expected, but...
d['xx'].append(5)   # *this doesn't!* -- d['xx'] is STILL range(4)!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']      # extracts the copy
temp.append(5)      # mutates the copy
d['xx'] = temp      # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()       # close it
于 2013-06-18T11:56:24.203 に答える