我可以使用Dictionary来存储我需要循环通过csv文件来查找的关键字吗?

时间:2015-07-22 18:09:03

标签: python csv dictionary

我正在编写一个python脚本,它将逐行查找csv文件以查找关键字。找到该关键字后,我需要将整行写入新的.csv文件。我在编写for循环以完成此任务时遇到问题,我不明白如何写入新的.csv文件。我将发布到目前为止我所做的工作。

#!/usr/bin/python

# First import csv module to work on .csv file
import csv

#Lets open the files that will be used to read from and write too
infile = open('infile.csv','rb')
outfile = open('outfile.csv','w')


# Lets pass file object through csv reader method
csv_f_reader = csv.reader(infile)
writer = csv.writer(outfile,delimiter=',',quotechar='',quoting=csv.QUOTE_NONE)
#Lets create a dictionary to hold all search words as unique keys.
# the associated value will be used to keep count of how many successful
# hits the forloop hits.

search_word={'wifi':0,'WIFI':0,'wi-fi':0,'Wi-Fi':0,'Cisco':0,'cisco':0,'NETGEAR':0,'netgear':0,'Netge$

for csv_line in csv_f_reader:
    match_found = False
    for keyword in search_word.keys():
            for csv_element in csv_line:
                    if keyword in csv_element:
                            match_found = True
                            search_word[keyword] +=1
    if match_found:
            writer.writerow(csv_line)


#Dont forget to close the file
infile.close()
outfile.close()
print search_word.keys(), search_word.values()

2 个答案:

答案 0 :(得分:1)

您真的不需要在这里使用字典作为关键字。呃...等等,哦,你想跟踪你看到每个关键词的次数。你的描述并没有这么说。

无论如何,你应该循环遍历文件和键中的行。循环应该看起来像这样:

for line in csv_f_reader:
    for keyword in search_word.keys():
        if keyword in line:
            search_word[keyword] += 1
            writer.write(line)

infile.close()
outfile.close()

我没有仔细检查过您是否正确使用了csv模块,但这应该可以让您知道它应该是什么样子。

答案 1 :(得分:0)

您不需要为您所描述的内容添加字典(除非您尝试计算关键字实例)。 search_word.keys()无论如何都会给你一个清单。

首先,您想要像这样迭代csv:

infile = open('infile.csv')
csv_f_reader = csv.reader(infile)
for csv_line in csv_f_reader:
    print csv_line

如果您尝试这样做,您会看到每一行都会为您提供所有元素的列表。您可以使用关键字列表来比较每个关键字并编写通过的关键字

for csv_line in csv_f_reader:
    for k in search_word.keys():
        if k in csv_line:
             writer.writerow(csv_line)

在您的情况下,关键字与CSV元素完全相同,它们位于其中。我们可以通过检查子串的元素来处理这个问题:

for csv_line in csv_f_reader:
    match_found = False
    for k in search_word.keys():
        for csv_element in csv_line:
            if k in csv_element:
                match_found = True
    if match_found:
        writer.writerow(csv_line)

另一件事是,您需要在写入模式下打开输出文件:

outfile = open('outfile.csv', 'w')