【发布时间】:2018-05-30 07:23:04
【问题描述】:
我有一个关键字 healthy_list 列表,我想在 csv 文件的列中进行检查。如果列表中至少有一个关键字出现,那么我将整行写入一个新的 csv 文件。
我使用 re.search 检查关键字,然后记录行号,然后使用 csv.writer 编写新的 csv。但是包含关键字的许多行没有显示在我的新 csv 文件中。请问有cmets吗?
healthy_new=[]
with open("Data 2017.csv","rb") as f:
csvreader=csv.reader(f,delimiter=",")
next(csvreader)
for line, row in enumerate(csvreader):
for word in healthy_list:
try:
if (re.search(word,row[4].lower()) ):
healthy_new.append(line)
except ValueError:
continue
healthy_new=list(set(healthy_new))
....
f = open("Data 2017.csv", "r")
reader = csv.reader(f)
data = open("healthy_new_output.csv", "w")
w = csv.writer(data, delimiter=',')
for idx, row in enumerate(reader):
idx+=-1
if idx in healthy_new:
my_row = row
w.writerow(my_row)
编辑: 一些数据切片 2017.csv Data 2017.csv
健康列表:
[...'diet', 'low-fat', 'light', 'diet', 'salad', 'salads', 'baked', 'grilled', 'whole grain']
【问题讨论】:
-
我们能得到
'Data 2017.csv'和healthy_list的例子吗? -
如果你只想要一个包含测试的字符串,为什么还要使用
re? -
@Megalng这是迄今为止我学到的唯一方法...您建议哪种方法?