我已经制作了这个CSV文件来玩。从我以前告诉过的,我很确定这个CSV文件是有效的,可以在这个例子中使用。搜索CSV文件(Python)
基本上我有这个CSV文件“book_list.csv”:
name,author,year
Lord of the Rings: The Fellowship of the Ring,J. R. R. Tolkien,1954
Nineteen Eighty-Four,George Orwell,1984
Lord of the Rings: The Return of the King,J. R. R. Tolkien,1954
Animal Farm,George Orwell,1945
Lord of the Rings: The Two Towers, J. R. R. Tolkien, 1954
而且我也有这个文本文件“search_query.txt”,因此我把我要搜索的关键字,结果搜索字词CSV文件:
Lord
Rings
Animal
我现在想出了一些代码(用的东西,我读过的帮助下),让我来算匹配条目的数量。然后我有程序写一个单独的CSV文件'results.csv',它只返回'匹配'或''。
该程序然后采用这个'results.csv'文件并计算我有多少'匹配'结果,并打印计数。
import csv
import collections
f1 = file('book_list.csv', 'r')
f2 = file('search_query.txt', 'r')
f3 = file('results.csv', 'w')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
input = [row for row in c2]
for booklist_row in c1:
row = 1
found = False
for input_row in input:
results_row = []
if input_row[0] in booklist_row[0]:
results_row.append('Matching')
found = True
break
row = row + 1
if not found:
results_row.append('')
c3.writerow(results_row)
f1.close()
f2.close()
f3.close()
d = collections.defaultdict(int)
with open("results.csv", "rb") as info:
reader = csv.reader(info)
for row in reader:
for matches in row:
matches = matches.strip()
if matches:
d[matches] += 1
results = [(matches, count) for matches, count in d.iteritems() if count >= 1]
results.sort(key=lambda x: x[1], reverse=True)
for matches, count in results:
print 'There are', count, 'matching results'+'.'
在这种情况下,我的输出回报:
There are 4 matching results.
我敢肯定有这样做的,避免写一个完全独立的CSV文件的一个更好的办法..但对我来说这是比较容易让我的头靠近。
我的问题是,我已经放在一起的这段代码只返回有多少匹配的结果。如何修改它以便返回ACTUAL结果呢?
即我希望我的输出返回:
There are 4 matching results.
Lord of the Rings: The Fellowship of the Ring
Lord of the Rings: The Return of the King
Animal Farm
Lord of the Rings: The Two Towers
正如我所说的,我敢肯定有一个更简单的方法做什么我已经有..所以一些见解将是有益的。 :)
干杯!
编辑:我只是意识到,如果我的关键字是小写,它不会工作..有没有办法避免区分大小写?