2017-04-23 79 views
-1

我正在嘗試在文本文件中存儲語句的正負分數。我想將分數存儲在csv文件中。我已經實現瞭如下代碼:Python - 在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循環。

Traceback (most recent call last):

File "C:\Users\pc\AppData\Local\Programs\Python\Python36-32\classifier.py", line 21, in for val in pos_score: TypeError: 'float' object is not iterable

回答

2

你必須與你的代碼的幾個誤區:

你的代碼和錯誤並不相互對應。

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

pos_score是浮法所以兩者都是錯誤range()需要一個intfor val需要一個iterable。您希望從哪裏獲得您的價值清單?
而且從使用它看起來像你,因爲你也在使用generator expression期待list of list of valueswriterow

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>) 
+0

感謝您的幫助 –