我正在寻找一种方法,从一个相当大的python数据库中提取行。我只需要保留那些包含我的关键字之一。我想我可以使用正则表达式来解决这个问题,并且我已经将下面的代码组合在一起。不幸的是,它给了我一些错误(可能也是因为我的关键字在文件listtosearch.txt中写在单独的行中,数量确实很大,接近500个)。
import re
data = open('database.txt').read()
fileout = open("fileout.txt","w+")
with open('listtosearch.txt', 'r') as f:
keywords = [line.strip() for line in f]
pattern = re.compile('|'.join(keywords))
for line in data:
if pattern.search(line):
fileout.write(line)我还尝试使用双循环(在关键字列表和数据库行中),但运行起来太耗时了。
我得到的错误是:
Traceback (most recent call last):
File "/usr/lib/python2.7/re.py", line 190, in compile
return _compile(pattern, flags)
File "/usr/lib/python2.7/re.py", line 240, in _compile
p = sre_compile.compile(pattern, flags)
File "/usr/lib/python2.7/sre_compile.py", line 511, in compile
"sorry, but this version only supports 100 named groups"
AssertionError: sorry, but this version only supports 100 named groups有什么建议吗?谢谢
发布于 2013-06-27 19:29:25
下面是我的代码:
import re
data = open('database.txt', 'r')
fileout = open("fileout.txt","w+")
with open('listtosearch.txt', 'r') as f:
keywords = [line.strip() for line in f]
# one big pattern can take time to match, so you have a list of them
patterns = [re.compile(keyword) for keyword in keywords]
for line in data:
for pattern in patterns:
if not pattern.search(line):
break
else:
fileout.write(line)我使用以下文件对其进行了测试:
database.txt
"Name jhon" (1995)
"Name foo" (2000)
"Name fake" (3000)
"Name george" (2000)
"Name george" (2500)listtosearch.txt
"Name (george)"
\(2000\)这就是我在fileout.txt中得到的
"Name george" (2000)所以这应该也能在你的机器上工作。
发布于 2013-06-27 20:26:46
你可能想看看Aho–Corasick string matching algorithm。可以在here中找到python中的一个工作实现。
此模块的一个简单示例用法:
from pyahocorasick import Trie
words = ['foo', 'bar']
t = Trie()
for w in words:
t.add_word(w, w)
t.make_automaton()
print [a for a in t.iter('my foo is a bar')]
>> [(5, ['foo']), (14, ['bar'])]在你的代码中集成应该是简单的。
发布于 2013-06-27 18:44:35
首先,我很确定你指的是data = open('database.txt').readlines()而不是read()。否则,data将是一个字符串,而不是一列行,并且您的for line in data没有任何意义。
在这一点上,你实际上是在寻找一个按关键字索引的解决方案,而朴素的搜索将失去足够的效率来给你一个及时的结果。
真的没有比这更高效或者更简单的方法了。您将不得不咬紧牙关,接受查看整个数据库的成本。
此外,如果您的数据库完全可以放入内存中,那么它也不会那么大:)
也就是说,你还可以用其他方法来做这件事,可能会更有效率:
data = open('database.txt').readlines() fileout = open("fileout.txt","w+") with open('listtosearch.txt','r') as f: keywords = line.strip() for line in f关键字=设置(关键字) for line in data:#您可能需要更聪明地将行拆分为#将标点符号之类的东西考虑在内。对于line.split()中的单词:如果关键字中的单词:fileout.write(行)断开
Here是一个考虑了标点符号的单词拆分的例子。
https://stackoverflow.com/questions/17340703
复制相似问题