2016-11-13 6 views
2

내가 두 개의 열이 트윗 하나와 형식의 감정 값에 대한 다른이있는 .CSV 파일이 같은 (그러나 트윗 수천) :이 같은 출력을 좀하고 싶습니다CSV 파일의 행을 튜플 목록으로 변환 하시겠습니까?

I like stackoverflow,Positive 
Thanks for your answers,Positive 
I hate sugar,Negative 
I do not like that movie,Negative 
stackoverflow is a question and answer site,Neutral 
Python is oop high-level programming language,Neutral 

:

negfeats = [('I do not like that movie','Negative'),('I hate sugar','Negative')] 
posfeats = [('I like stackoverflow','Positive'),('Thanks for your answers','Positive')] 
neufeats = [('stackoverflow is a question and answer site','Neutral'),('Python is oop high-level programming language','Neutral')] 

나는 아래에서 이것을 시도했지만 터플에서 누락 된 문자가 있습니다. 또한 x, y 및 z를 정수가 아닌 부동 소수점으로 유지하는 방법은 무엇입니까?

import csv 
neg = ['Negative'] 
pos = ['Positive'] 
neu = ['Neutral'] 
neg_counter=0 
pos_counter=0 
neu_counter=0 
negfeats = [] 
posfeats = [] 
neufeats = [] 
with open('ff_tweets.csv', 'Ur') as f: 
    for k in f: 
     if any(word in k for word in neg): 
      negfeats = list(tuple(rec) for rec in csv.reader(f, delimiter=',')) 
      neg_counter+=1 
     elif any(word in k for word in pos): 
      posfeats = list(tuple(rec) for rec in csv.reader(f, delimiter=',')) 
      pos_counter+=1 
     else: 
      neufeats = list(tuple(rec) for rec in csv.reader(f, delimiter=',')) 
      neu_counter+=1 
x = neg_counter * 3/4 
y = pos_counter * 3/4 
z = neu_counte * 3/4 
print negfeats 
print posfeats 
print neufeats 
print x 
print y 
print z 

답변

0

import csv 

neg = 'Negative' 
pos = 'Positive' 
neu = 'Neutral' 
negfeats = [] 
posfeats = [] 
neufeats = [] 

with open('ff_tweets.csv', 'Ur') as f: 
    for r in csv.reader(f): 
     if r[1] == neg: 
      negfeats.append((r[0], r[1])) 
     if r[1] == pos: 
      posfeats.append((r[0], r[1])) 
     if r[1] == neu: 
      neufeats.append((r[0], r[1])) 

x = len(negfeats) * float(3)/4 
y = len(posfeats) * float(3)/4 
z = len(neufeats) * float(3)/4 

print negfeats 
print posfeats 
print neufeats 
print x 
print y 
print z 
+1

당신은 조심해야한다 - 파이썬 2.7 0'''3/4' 반환 (문제에서와 같이). – will

+0

@will 사실, 그냥 수정하자. –

+0

@ ÉbeIsaac이 솔루션은 이론적으로는 작동해야하지만, 실행할 때 negfeats, posfeats 및 neufeats에 대한 빈 목록이 있습니다. – Alsphere

0

가 팬더를 사용하여,이 시도 작동합니다. '감정'은 csv 파일의 열입니다 :

import pandas as pd 

df = pd.read_csv('ff_tweets.csv') 

pos = tuple(df.loc[df['Sentiment'] == 'Positive'].apply(tuple, axis = 1)) 
neu = tuple(df.loc[df['Sentiment'] == 'Neutral'].apply(tuple, axis = 1)) 
neg = tuple(df.loc[df['Sentiment'] == 'Negative'].apply(tuple, axis = 1)) 

print pos, neg, neu 

출력 :

(('I like stackoverflow', 'Positive'), ('Thanks for your answers', 'Positive')) (('I hate sugar', 'Negative'), ('I do not like that movie', 'Negative')) (('stackoverflow is a question and answer site', 'Neutral'), ('Python is oop high-level programming language', 'Neutral')) 
+0

포지션 라인 코드가 어떤 역할을하는지 설명해 주시겠습니까? – Alsphere

+0

'pos'= 긍정, 'neg'= 음수, 'neu'= 중립 –

+0

각각이 별개의 튜플 –

관련 문제