【问题标题】:How to search content of a list from a large file quickly?如何快速从大文件中搜索列表内容?
【发布时间】:2021-07-03 06:35:00
【问题描述】:

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

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

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

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

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

【问题讨论】:

  • 请了解更多详情。你能用几行文件来编辑你的帖子吗?你需要经常搜索这个文件吗?你的用例是什么?
  • @Corralien,我必须循环运行我的程序来创建来自不同城市的人的单独文件。链接到我的 CSV 文件的几行:pastebin.com/SAh8TcAY
  • 该行倒数第二部分是城市
  • 文件的第一行是标题(列名)吗?
  • 不,它没有标题

标签: python python-3.x csv


【解决方案1】:

您可以将文件转换为数据库 (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)

【讨论】:

  • 非常感谢@Corralien 回答我的问题,它确实帮助了我。我真的很想投票,但是我这样做是因为我的声誉很低。很抱歉。
猜你喜欢
  • 2011-11-22
  • 2010-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-14
相关资源
最近更新 更多