Skip to main content
 首页 » 编程设计

python之从 csv 中提取数据

2025年02月15日8cloudgamer

我有一个 csv 文件,每一行都包含形容词列表。

例如前2行如下:

["happy","sad","colorful"] 
["horrible","sad","cheerful","happy"] 

我想从此文件中提取所有数据,以得到一个只包含每个形容词的列表。 (在这里,它将是一个列表,如下所示:

["happy","sad","colorful","horrible","cheerful"] 

我正在使用 Python 执行此操作。

import csv 
with open('adj.csv', 'rb') as f:  
    reader = csv.reader(f)  
    adj_list = list(reader)  
    filtered_list = []  
    for l in adj_list:  
        if l not in new_list:  
            filtered_list.append(l) 

请您参考如下方法:

假设“内存不重要”并且您正在寻找一个衬垫:

from itertools import chain 
from csv import reader 
 
print(list(set(chain(*reader(open('file.csv')))))) 

具有这样的“file.csv”内容:

happy, sad, colorful 
horrible, sad, cheerful, happy 

输出:

['可怕', '多彩', '悲伤', '快乐', '快乐', '快乐']

如果您不介意收到一个 Python 集 而不是一个列表,您可以删除 list() 部分。