【发布时间】:2011-08-30 03:28:27
【问题描述】:
我已经制作了这个 CSV 文件以供使用。根据我之前被告知的内容,我很确定这个 CSV 文件是有效的并且可以在这个示例中使用。
基本上我有这个 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 文件。但这对我来说更容易理解。
我的问题是,我放在一起的这段代码只返回有多少匹配结果.. 我如何修改它才能返回实际结果?
即我希望我的输出返回:
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
正如我所说,我确信有一种更简单的方法可以完成我已有的工作。所以一些见解会有所帮助。 :)
干杯!
编辑:我刚刚意识到,如果我的关键字是小写的,它将不起作用.. 有没有办法避免区分大小写?
【问题讨论】: