gpt4 book ai didi

python - 在文本中搜索一长串子字符串

转载 作者:太空宇宙 更新时间:2023-11-03 11:08:20 24 4
gpt4 key购买 nike

问题:给定一组约 250000 个整数用户 ID,以及大约 TB 的 JSON 格式的每行记录,将用户 ID 与数据库匹配的记录加载。

所有记录中只有大约 1% 会与 250000 个用户 ID 匹配。我尝试使用字符串匹配来确定用户 ID 是否在原始 JSON 中,而不是 JSON 解码每条记录,这需要很长时间;如果匹配,则解码 JSON 并检查记录,然后插入。

问题是将一个原始 JSON 字符串与包含 ~250k 字符串条目的集合进行匹配很慢。

这是目前的代码:

// get the list of integer user IDs
cur.execute('select distinct user_id from users')

// load them as text into a set
users = set([])
for result in cur.fetchall():
users.add(str(result[0]))

// start working on f, the one-json-record-per-line text file
for line in f:
scanned += 1
if any(user in line for user in users):
print "got one!"
// decode json
// check for correct decoded user ID match
// do insert

我的处理方式正确吗?匹配这些字符串的更快方法是什么?目前,在查找如此多的用户 ID 时,这在 3ghz 机器上每秒管理 ~2 个条目(不太好)。当用户 ID 列表很短时,它管理大约 200000 个条目/秒。

最佳答案

Aho-Corasick似乎是为此目的而 build 的。甚至还有一个方便的 Python 模块 (easy_install ahocorasick)。

import ahocorasick

# build a match structure
print 'init empty tree'
tree = ahocorasick.KeywordTree()

cur.execute('select distinct user_id from users')

print 'add usernames to tree'
for result in cur.fetchall():
tree.add(str(result[0]))

print 'build fsa'
tree.make()

for line in f:
scanned += 1
if tree.search(line) != None:
print "got one!"

这接近每秒约 450 个条目。

关于python - 在文本中搜索一长串子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13458481/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com