如果您有1000个短语,并且您在搜索输入字符串以查找其中哪些短语是子字符串,那么您可能不会对使用大正则表达式获得的性能感到满意。一个trie是一个更多的工作要实现,但它更有效率:正则表达式a|b|c|d|e
对给定输入字符串中的每个字符执行五个测试,而一个只有一个字符串。您也可以使用产生DFA的词法分析器,如Plex。
编辑:
我出现在这个早上被拖延。试试这个:
class Trie(object):
def __init__(self):
self.children = {}
self.item = None
def add(self, item, remainder=None):
"""Add an item to the trie."""
if remainder == None:
remainder = item
if remainder == "":
self.item = item
else:
ch = remainder[0]
if not self.children.has_key(ch):
self.children[ch] = Trie()
self.children[ch].add(item, remainder[1:])
def find(self, word):
"""Return True if word is an item in the trie."""
if not word:
return True
ch = word[0]
if not self.children.has_key(ch):
return False
return self.children[ch].find(word[1:])
def find_words(self, word, results=None):
"""Find all items in the trie that word begins with."""
if results == None:
results = []
if self.item:
results.append(self.item)
if not word:
return results
ch = word[0]
if not self.children.has_key(ch):
return results
return self.children[ch].find_words(word[1:], results)
快速测试(words.txt
是BSD字的文件,一个非常方便的事情有大约 - 它包含了约24个字):
>>> t = Trie()
>>> with open(r'c:\temp\words.txt', 'r') as f:
for word in f:
t.add(word.strip())
这需要在15秒左右我机。然而,这几乎是瞬间:
>>> s = "I played video games in a drunken haze."
>>> r = []
>>> for i in range(len(s)):
r.extend(t.find_words(s[i:]))
>>> r
['I', 'p', 'play', 'l', 'la', 'lay', 'a', 'ay', 'aye', 'y', 'ye', 'yed', 'e', 'd', 'v', 'video', 'i', 'id', 'ide', 'd', 'de', 'e', 'o', 'g', 'ga', 'gam', 'game', 'a', 'am', 'ame', 'm', 'me', 'e', 'es', 's', 'i', 'in', 'n', 'a', 'd', 'drunk', 'drunken', 'r', 'run', 'u', 'un', 'unken', 'n', 'k', 'ken', 'e', 'en', 'n', 'h', 'ha', 'haze', 'a', 'z', 'e']
是,unken
是words.txt。我不知道为什么。
哦,我也尝试用正则表达式来比较:
>>> import re
>>> with open(r'c:\temp\words.txt', 'r') as f:
p = "|".join([l.strip() for l in f])
>>> p = re.compile(p)
Traceback (most recent call last):
File "<pyshell#250>", line 1, in <module>
p = re.compile(p)
File "C:\Python26\lib\re.py", line 188, in compile
return _compile(pattern, flags)
File "C:\Python26\lib\re.py", line 241, in _compile
p = sre_compile.compile(pattern, flags)
File "C:\Python26\lib\sre_compile.py", line 529, in compile
groupindex, indexgroup
OverflowError: regular expression code size limit exceeded
好样的。我在该块内有一块我正在寻找的文本和短语。我正在通过这样的正则表达式来做: >>> text_input =“这是第一个短语和第三个短语” >>> regex =“第一个短语|第二个短语|第三个短语” > >> p = re.compile(regex,re.I) >>> p.findall(text_input) ['first phrase','second phrase'] – 2009-12-04 13:59:25
FWIW,集合理解语法是python 3.0及更高版本。 – hughdbrown 2009-12-04 14:46:33
@hughdbrown:我没有使用集合理解,我使用新风格的集合文字http://docs.python.org/3.1/whatsnew/3.0.html#new-syntax这里的一切都可以在py 2中完成。 x通过使用'set(lst)' – SilentGhost 2009-12-04 14:59:35