首页 > 解决方案 > 如何快速从大文件中搜索列表内容?

问题描述

我有一个 CSV 文件,大小为 3 GB。

我想快速从该文件中搜索列表的内容。

有人建议将 CSV 转换为 BLF 文件并应用布隆过滤器。

我是初学者,对此我一无所知。

如果有人可以提供简短的工作代码或指向具有相同详细说明的页面的链接,那将非常有帮助。

标签: pythonpython-3.xcsv

解决方案


您可以将文件转换为数据库 (SQLite):

import csv, sqlite3

# Change column names
fields = ('code1', 'code2', 'firstname', 'lastname', 'genre', 'city', 'country')

# Create the database and the unique table
con = sqlite3.connect("data.db")
cur = con.cursor()
cur.execute(f"CREATE TABLE tbl {fields};")

# Read the csv file and insert rows to database
reader = csv.reader(open('data.csv'))
cur.executemany(f"INSERT INTO tbl {fields} VALUES (?, ?, ?, ?, ?, ?, ?);", reader)

# Create some indexes to increase speed of queries
cur.execute("CREATE INDEX idx_fullname ON tbl (firstname, lastname);")
cur.execute("CREATE INDEX idx_location ON tbl (city, country);")

# Commit and close (Mandatory!)
con.commit()
con.close()

之后,您可以选择查询数据库:

  • sqlite浏览器
  • Python/sqlite(与上面类似,但带有 SELECT 语句)
  • 熊猫 ( pd.read_sql )

推荐阅读