python - 如何快速从大文件中搜索列表内容?
问题描述
我有一个 CSV 文件,大小为 3 GB。
我想快速从该文件中搜索列表的内容。
有人建议将 CSV 转换为 BLF 文件并应用布隆过滤器。
我是初学者,对此我一无所知。
如果有人可以提供简短的工作代码或指向具有相同详细说明的页面的链接,那将非常有帮助。
解决方案
您可以将文件转换为数据库 (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 )
推荐阅读
- angular - Angular 6 - 在单击的项目上切换类别并在其他项目上切换类别
- laravel - 无法将 str_random() 生成的数字存储到 MySQL
- bash - 将文本文件集的内容复制到其他文本文件集
- c++ - 将 $(location) 传递给 Bazel --test_arg
- python - Python 3 中的服务目录
- kubernetes - Kubernetes 节点未就绪:ContainerGCFailed / ImageGCFailed 上下文期限已超过
- php - SEO 问题 Google 将我的网站 URL 编入索引两次
- c - 循环中的表格未正确显示数据
- git - 在推送到 github 时,! [rejected] master -> master (fetch first) error: failed to push some refs to "
" - ajax - 如何正确地将 ajax 函数重写为 Reactjs 等效项