- android - 多次调用 OnPrimaryClipChangedListener
- android - 无法更新 RecyclerView 中的 TextView 字段
- android.database.CursorIndexOutOfBoundsException : Index 0 requested, 光标大小为 0
- android - 使用 AppCompat 时,我们是否需要明确指定其 UI 组件(Spinner、EditText)颜色
问题:给定一组约 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/
我正在尝试创建一个程序,其中字符串的前三个字符重复给定次数,如下所示: foo('Chocolate', 3) # => 'ChoChoCho' foo('Abc', 3) # => 'AbcAbcA
我有以下字符串: std::string str = "Mode:AAA:val:101:id:A1"; 我想分离一个位于 "val:" 和 ":id" 之间的子字符串,这是我的方法: std::st
DNA 字符串可以是任意长度,包含 5 个字母(A、T、G、C、N)的任意组合。 压缩包含 5 个字母(A、T、G、C、N)的 DNA 字母串的有效方法是什么?不是考虑每个字母表 3 位,我们可以使用
是否有一种使用 levenstein 距离将一个特定字符串与第二个较长字符串中的任何区域进行匹配的好方法? 例子: str1='aaaaa' str2='bbbbbbaabaabbbb' if str
使用 OAuth 并使用以下函数使用我们称为“foo”(实际上是 OAuth token )的字符串加密 key public function encrypt( $text ) { // a
我是一名优秀的程序员,十分优秀!