简体   繁体   English

如何检查列表中的项目是否出现在csv中?

[英]How to check if an item in a list appears in csv?

I have a list of items: 我有一个项目列表:

List = ['apple', 'banana', 'orange']

and a csv file: 和一个csv文件:

apple
kiwi
banana
orange
pear

I am trying to see for each item in the list if it matches the first column of the csv, and if it does, append a '1' to the end of the row (otherwise appending a '0'), but I am a bit lost. 我试图查看列表中的每个项目是否与csv的第一列匹配,如果匹配,则在行的末尾添加“1”(否则附加“0”),但我是有点失落。 The code below is pretty much what I'm trying to get the end result to be. 下面的代码几乎就是我想要获得最终结果的代码。

apple, 1
kiwi, 0
banana, 1
orange, 1
pear, 0

I am very new to python and would really appreciate any help! 新的蟒蛇,真的希望任何帮助! Thanks 谢谢

Note that your csv file is rather a plain text file. 请注意,您的csv文件是纯文本文件。 But also a valid csv, so I'll treat it like one. 但也是一个有效的csv,所以我会把它当成一个。

Read line by line and print 0 or 1 alongside the data using a ternary expression. 逐行读取并使用三元表达式在数据旁边打印0或1。 Quick & easy, no dictionary or counters needed and preserves the order: 快速简便,无需字典或计数器并保留订单:

import csv

List = {'apple', 'banana', 'orange'}

with open("csv.csv") as f:
    cr = csv.reader(f)
    for row in cr:
        print("{}, {}".format(row[0],1 if row[0] in List else 0))

since it's not really a csv, basic line by line read will do too: 因为它不是真正的csv,基本的逐行读取也会这样做:

List = {'apple', 'banana', 'orange'}

with open("csv.csv") as f:
    for item in f:
        item = item.strip()
        print("{}, {}".format(item,1 if item in List else 0))

note that in both examples I have used a set , not a list . 请注意,在两个示例中,我使用了一个set ,而不是list Makes a difference speed-wise when there are a lot of items. 当有很多物品时,速度快。

Perhaps something like this. 也许这样的事情。 It'll read from the csv, count how many times each fruit is found in your list, then overwrite the csv file with the new data. 它将从csv中读取,计算列表中每个水果的次数,然后用新数据覆盖csv文件。

import csv

List = ['apple', 'banana', 'orange']
data = []
filename = 'file.csv'

with open(filename, newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        data.append(row)

for item in List:
    for fruit in data:
        if item in fruit:
            fruit[1] = int(fruit[1]) + 1

with open(filename, 'w', newline='') as f:
    writer = csv.writer(f)
    writer.writerows(data)

I tried below code, which will store result in CSV 我尝试了下面的代码,它将结果存储在CSV中

import csv

lists = ['apple', 'banana', 'orange']
nf = csv.writer(open("output.csv", "w"))
with open('input.csv', 'rb') as f:
    reader = csv.reader(f)
    for row in reader:
        if(''.join(row) in lists):
            nf.writerow([''.join(row),1])
        else:
            nf.writerow([''.join(row),0])

OUTPUT in CSV 以CSV格式输出

apple,1
kiwi,0
banana,1
orange,1
pear,0    

You can easily achieve this using the csv module in the Python standard library, specifically the csv.reader() method. 您可以使用Python标准库中的csv模块轻松实现此目的,特别是csv.reader()方法。

import csv

fruit_list = ['apple', 'banana', 'orange']
fruit_in_file = {}

with open('csv_file.csv', 'r') as csvfile:
    fruit_reader = csv.reader(csvfile)
    for row in fruit_reader:
        fruit = row[0]
        if fruit in fruit_list:
            fruit_in_file[fruit] = 1
        else:
            fruit_in_file[fruit] = 0

print(fruit_in_file)
>>> {'apple': 1, 'kiwi': 0, 'orange': 1, 'banana': 1, 'pear': 0}

After achieving this, it seems from your question that you want to write a csv file containing this data, so we'll iterate through our dict and write to a csv file using the csv.writer() method. 实现这一点后,从您的问题看来,您想要编写包含此数据的csv文件,因此我们将遍历我们的dict并使用csv.writer()方法写入csv文件 :

with open('new_csv_file.csv', 'w') as csvfile:
    fruit_writer = csv.writer(csvfile)
    for key, value in fruit_in_file.items():
        fruit_writer.writerow([key, value])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM