2014-04-12 110 views
0

我在做一个情感分析项目。(Python)CSV阅读器省略一行

我有以下格式csv文件:

|happy|,|I'm happy| 
|sad|,|Today is a bad day| 
|angry|,|I hate this| 
... 

甲字典类型变量被声明和用于存储不同的情感的计数。

count = {"happy":0, "sad":0, "angry":0} 

函数被定义为检索情绪和消息。

total_status = 0 
inpStatus = csv.reader(open(Filename, 'rb'), delimiter=',', quotechar='|') 
for row in inpStatus: 
    sentiment = row[0] 
    status = row[1] 
    total_status += 1 
... 
    for s in count: 
     if (sentiment == s): 
      count[s] += 1 

我发现,第一行(即|happy|,|I'm happy|)和文件的最后一行中的计数被跳过。而total_status省略了一行。 我以错误的方式写了分隔符吗? 为什么会发生这种情况,我应该如何重写程序?

+0

由于我在做utf-8文件导入,所以这里就是我的问题和解决方案! http://stackoverflow.com/questions/12561063/python-extract-data-from-file – user3526957

回答

0

嗯,其实我重写你的代码,它工作正常:

from csv import reader 

total_status = 0 
count = {'happy': 0, 'sad': 0, 'angry':0} 

for sentiment, status in reader(open(filepath, 'rb'), delimiter=',', quotechar='|'): 
    total_status += 1 
    count[sentiment] += 1 

但你的代码给出正确的结果了。

+0

哦,那是因为我的数据存储在csv文件中.. 感谢您的重写! – user3526957

+0

这正是我的想法。另外,如果需要计算序列的长度,最好存储对它的引用,就像你所做的那样,并且简单地调用len(inp_status),因为据我所知它是O(1)。 – slnowak