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

我不确定我是否完全理解这个问题,但我会试一试。

我建议使用matplotlib中的 csv 功能。如果您还没有听说过,matplotlib 是一个优秀的开源图形库。在www.matplotlib.org上查看。

from matplotlib import mlab
writer = mlab.csv.writer(open('results.csv', 'w'))    # pass an open file object and returns a csv writer

# Write the header
writer.writerow(['fileid', 'feature', 'resultant']) 

# Write the data in the same fashion
# ...

在 mlab 中使用 csv.reader() 重新打开 csv 文件将导入列表中的所有数据,而不是字符串。注意:这适用于任何 csv 格式的文件,而不仅仅是那些使用 csv.writer() 创建的文件。

于 2013-06-18T11:50:54.807 回答
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 回答