【发布时间】:2013-06-27 10:26:53
【问题描述】:
我正在寻找一种从 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
有什么建议吗?谢谢
【问题讨论】:
-
它给了我这些错误:pattern = re.compile('|'.join(keywords)) 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 support 100 named groups" AssertionError: sorry, but this version only support 100 named groups
-
好了,它告诉您正则表达式模式中的子表达式不能超过 100 个。不是你的错。布莱斯的回答会奏效。
-
实际上,即使我运行 Brice 的代码,它也会给我完全相同的错误:(
-
@user2447387 这是不可能的。我的代码没有使用
re模块,而且我没有违规行。 -
我知道,对不起,我的错!让我正常运行