2011-05-21 104 views
1

我已经制作了这个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 

正如我所说的,我敢肯定有一个更简单的方法做什么我已经有..所以一些见解将是有益的。 :)

干杯!

编辑:我只是意识到,如果我的关键字是小写,它不会工作..有没有办法避免区分大小写?

回答

0

总体规划:

  1. 在阅读整本书名单CSV成{title: info}字典。
  2. 阅读问题csv。对于每个关键词,过滤词典:

    [key for key, value in books.items() if "Lord" in key] 
    

    说。做你的结果。

  3. 如果你想,把结果放在另一个csv。

如果要处理套管问题,请将所有标题存储在字典中时尝试将所有标题转为小写("FOO".lower())。

1
  1. 扔掉查询文件并从sys.argv [1:]中获取您的搜索条件。

  2. 丢弃您的输出文件并改为使用sys.stdout。

  3. 将匹配的书目标题追加到result_list。您目前使用的result_row有一个相当令人误解的名字。您需要的计数是len(result_list)。打印。然后打印result_list的内容。

  4. 将查询字转换为小写一次(在开始读取输入文件之前)。读取每个book_list行时,将其标题转换为小写。用小写查询词和小写字母标题进行匹配。