简体   繁体   English

如何在csv文件中搜索存储在另一个csv文件中的关键字?

[英]How do I search a csv file for keywords stored in another csv file?

I'm trying to search a csv file having 150K+ row using keywords stored in a csv file with several dozen row. 我正在尝试使用存储在具有几十行的csv文件中的关键字来搜索具有150K +行的csv文件。 What's the best way to go about this? 最好的方法是什么? I've tried a few things but nothing has gotten me very far. 我尝试了一些东西,但没有什么能让我走得太远。

Current Code: 现行代码:

import csv
import pandas as pd
data = pd.read_csv('mycsv.csv')
for line in data:
    if 'Apple' in line:
        print(line)

This isn't what I want, it's just what I currently have. 这不是我想要的,这正是我现在所拥有的。 The for loop is my attempt at just getting output using one of the keywords from the smaller csv file. for循环是我尝试使用较小的csv文件中的一个关键字获取输出。 So far I'm either getting errors or there is no output. 到目前为止,我要么得到错误,要么没有输出。

Edit: I forgot to mention that the large csv file I'm trying to search from is from a web link, so I don't think with open is going to work 编辑:我忘了提到我正在尝试搜索的大型csv文件是来自网络链接,所以我不认为打开会工作

Supposing that your keywords are stored in a file named keys.csv and in each row of that file, there's only one keyword, like this: 假设您的关键字存储在名为keys.csv的文件中以及该文件的每一行中,则只有一个关键字,如下所示:

Orange
Apple
...

then try this: 试试这个:

with open('mycsv.csv') as mycsv, open('keys.csv') as keys:
    keys = keys.readlines()
    for line in mycsv:
        if any([key[:-2] in line for key in keys]):
            print(line)

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

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