我已经制作了这个 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”,该文件仅返回“Matching”或“”。
然后,程序获取此“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
正如我所说,我确信有一种更简单的方法可以做我已经拥有的事情......所以一些见解会有所帮助。 :)
干杯!
编辑:我刚刚意识到,如果我的关键字是小写,它将不起作用..有没有办法避免区分大小写?
最佳答案
丢弃查询文件并从 sys.argv[1:] 获取搜索词。
丢弃输出文件并使用 sys.stdout 代替。
将匹配的书目标题附加到 result_list。您当前拥有的 result_row 有一个相当具有误导性的名称。您想要的计数是
len(result_list)
。打印出来。然后打印result_list的内容。将查询词转换为小写一次(在开始读取输入文件之前)。当您阅读 book_list 的每个行时,将其标题转换为小写。使用小写查询词和小写标题进行匹配。
关于python - 搜索 CSV 文件 (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6080490/