简体   繁体   English

有没有办法用python在csv中搜索多组单词?

[英]Is there a way to search for multiple groups of words in a csv with python?

Ok, so I'm searching for two list of keywords in a csv file and I'm trying to save them as two different documents.好的,所以我正在 csv 文件中搜索两个关键字列表,并尝试将它们另存为两个不同的文档。

Here is my script.这是我的脚本。

import csv

with open ("kijiji_db.csv", "r", encoding="utf-8") as file:
     file_reader = csv.reader(file)
     listOfKeyWords = [["universite de montreal", "udem", "udm"], ["mil"]]

     for keywords in listOfKeyWords:
        resultats = []
        for keyword in keywords:
          for row in file_reader:
            if (keyword.lower() in row[5].lower() or keyword.lower() in row[1].lower()) and [row[1], row[2], row[3], row[4], row[5], row[7], row[8], row[9]] not in resultats:
                #print ("trouvé:", keyword)
                resultats.append([row[1], row[2], row[3], row[4], row[5], row[7], row[8], row[9]])
        print(resultats)
        with open("resultats_" + keywords[0] + ".csv", "w", encoding="utf-8") as file:
            writer = csv.writer(file)
            writer.writerows(resultats)
file.close()

Everything seems to work except that the second set of words (ie: "mil") give me an empty result.除了第二组单词(即:“mil”)给我一个空结果之外,一切似乎都有效。 Also, it creates the csv file, but it's also empty.此外,它会创建 csv 文件,但它也是空的。

I'm not sure, but I think the problem is very similar to this post: Why can't I call read() twice on an open file?我不确定,但我认为问题与这篇文章非常相似: 为什么我不能在打开的文件上调用 read() 两次? . . The problem here was that you could not read an open file twice, since the read cursor is left at the end of the document.这里的问题是您无法两次读取打开的文件,因为读取光标位于文档末尾。

If I'm right you could either open the file inside of the for keywords in listOfKeyWords: loop or use something like file_reader.seek(0).如果我是对的,您可以for keywords in listOfKeyWords: loop 中的for keywords in listOfKeyWords:内打开文件,或者使用类似 file_reader.seek(0) 的内容。 I've never used seek(0) before, but since it is the accepted answer in the other stackoverflow post, i'll assume that is should work too.我以前从未使用过 seek(0),但由于它是其他 stackoverflow 帖子中已接受的答案,因此我认为它也应该有效。

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

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