Python - 将浮点值存储在CSV文件中

时间:2017-04-23 11:58:14

标签: python-3.x csv

我试图将语句的正面和负面分数存储在文本文件中。我想将分数存储在csv文件中。我已经实现了下面给出的代码:

import openpyxl
from nltk.tokenize import sent_tokenize
import csv
from senti_classifier import senti_classifier
from nltk.corpus import wordnet

file_content = open('amazon_kindle.txt')

for lines in file_content:
    sentence = sent_tokenize(lines)
    pos_score,neg_score = senti_classifier.polarity_scores(sentence)

    with open('target.csv','w') as f:
        writer = csv.writer(f,lineterminator='\n',delimiter=',')

    for val in range(pos_score):
        writer.writerow(float(s) for s in val[0])
    f.close()

但代码在for循环中显示以下错误。

  

追踪(最近一次呼叫最后一次):

     

文件" C:\ Users \ pc \ AppData \ Local \ Programs \ Python \ Python36-32 \ classifier.py",   第21行,in为pos_score中的val:TypeError:' float'对象不可迭代

1 个答案:

答案 0 :(得分:2)

您的代码有几处错误:

您的代码和错误彼此不一致。

for val in pos_score:  # traceback
for val in range(pos_score):  #code

pos_score是一个浮点数,因此两者都是错误range()需要intfor val需要iterable。您希望从哪里获取您的价值清单?
从使用情况来看,您似乎期待list of list of values,因为您还在generator expression

中使用了writerow
writer.writerow(float(s) for s in val[0])

也许你只是期待一个值列表,这样你就可以摆脱for循环并只使用:

writer.writerow(float(val) for val in <list_of_values>)

使用:

with open('target.csv','w') as f:

表示您不再需要致电f.close()with关闭with块末尾的文件。这也意味着writerow()需要with块:

with open('target.csv','w') as f:
    writer = csv.writer(f,lineterminator='\n',delimiter=',')
    writer.writerow(float(val) for val in <list_of_values>)