csv模块:有序字典操作



我有一个csv,有两个字段,"positive"one_answers"negative"。我正在尝试使用DictReader((模块将csv中的阳性单词添加到列表中。这是以下代码。

import csv
with open('pos_neg_cleaned.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)


positive_list = []
for n in csv_reader:
if n == 'positive' and csv_reader[n] != None :
positive_list.append(csv_reader[n])

但是,程序返回一个空列表。知道如何解决这个问题吗?或者我做错了什么?

这是因为您只能从csv_reader生成器中读取一次。在这种情况下,您可以使用print语句来执行此操作。

只要稍微重新安排一下,它就会正常工作:

import csv
with open('pos_neg_cleaned.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
positive_list = []
for n in csv_reader:
# put your print statement inside of the generator loop. 
# otherwise the generator will be empty by the time your run the logic.
print(n)
# as n is a dict, you want to grab the right value from that dict.  
# if it contains a value, then do something with it.
if n['positive']:
# Here you want to call the value from your dict.  
# Don't try to call the csv_reader - but use the given data.
positive_list.append(n['positive'])

DictReader中的每一行都是一个字典,因此您可以检索"列值";使用列名作为";键";像这样:

positive_column_values = []
for row in csv_dict_reader:
positive_column_value = row["positive"]
positive_column_values.append(positive_column_value)

在执行该代码之后;positive_column_values";将具有来自"0"的所有值;"正";柱

您可以用您的代码替换此代码以获得所需结果:

import csv
with open('pos_neg_cleaned.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
positive_list = []
for row in csv_reader:
positive_list.append(row["positive"])
print(positive_list)

这里有一个简单的列表理解方法。它假设有一个名为header的头,它保存(或(positivenegative值。

import csv
with open('pos_neg_cleaned.csv', 'r') as csv_file:
csv_reader = csv.DictReader(csv_file)
positive_list = [line for line in csv_reader if line.get('header') == 'positive']
print(positive_list)

或者,如果csv的标题是positive:

positive_list = [line for line in csv_reader if line.get('positive')]

最新更新