加快执行速度,Python
加快执行速度,Python,python,performance,for-loop,spell-checking,Python,Performance,For Loop,Spell Checking,for循环在执行时间上非常昂贵。我正在建立一个修正算法,我使用了彼得·诺维格的拼写修正代码。我对它做了一点修改,意识到在数千字上执行优化需要花费太长时间 该算法检查1和2编辑距离并进行校正。我成功了。所以这可能会增加时间(我不确定)。以下是结尾的一部分,其中出现频率最高的单词用作参考: def correct(word): candidates = (known([word]).union(known(edits1(word)))).union(known_edits2(word).un
for
循环在执行时间上非常昂贵。我正在建立一个修正算法,我使用了彼得·诺维格的拼写修正代码。我对它做了一点修改,意识到在数千字上执行优化需要花费太长时间
该算法检查1和2编辑距离并进行校正。我成功了。所以这可能会增加时间(我不确定)。以下是结尾的一部分,其中出现频率最高的单词用作参考:
def correct(word):
candidates = (known([word]).union(known(edits1(word)))).union(known_edits2(word).union(known_edits3(word)) or [word]) # this is where the problem is
candidate_new = []
for candidate in candidates: #this statement isnt the problem
if soundex(candidate) == soundex(word):
candidate_new.append(candidate)
return max(candidate_new, key=(NWORDS.get))
而且,在候选者中,候选者的语句似乎在增加执行时间。您可以轻松查看peter norvig的代码,单击。我已经解决了这个问题。在声明中
candidates = (known([word]).union(known(edits1(word)))
).union(known_edits2(word).union(known_edits3(word)) or [word])
在哪里,
def known_edits3(word):
return set(e3 for e1 in edits1(word) for e2 in edits1(e1)
for e3 in edits1(e2) if e3 in NWORDS)
可以看出,edits3
中有3个for循环,这将执行时间增加了3倍<代码>编辑2有2个for循环。这就是罪魁祸首
如何最小化此表达式?
可以
itertools。重复帮助解决此问题???这里有几种提高性能的方法:
使用列表理解(或生成器)
不要在每次迭代中计算相同的东西
该守则将简化为:
def correct(word):
candidates = (known([word]).union(known(edits1(word)))).union(known_edits2(word).union(known_edits3(word)) or [word])
# Compute soundex outside the loop
soundex_word = soundex(word)
# List compre
candidate_new = [candidate for candidate in candidates if soundex(candidate) == soundex_word]
# Or Generator. This will save memory
candidate_new = (candidate for candidate in candidates if soundex(candidate) == soundex_word)
return max(candidate_new, key=(NWORDS.get))
另一个增强是基于这样一个事实,即您只需要MAX候选者
def correct(word):
candidates = (known([word]).union(known(edits1(word)))).union(known_edits2(word).union(known_edits3(word)) or [word])
soundex_word = soundex(word)
max_candidate = None
max_nword = 0
for candidate in candidates:
if soundex(candidate) == soundex_word and NWORDS.get(candidate) > max_nword:
max_candidate = candidate
return max_candidate
与什么相比,增加执行时间?首先尝试列表理解,看看这是否会改善情况:candidate\u new=[candidates for candidates in candidates if soundex(candidate)==soundex(word)]
@Evert我很好奇,但为什么列表理解会产生任何可测量的影响?@HannesOvrén,Onc原因:列表理解不会在每次迭代中调用append
方法。必须实际尝试,是的,似乎就是这样。谢谢我不知道这其实很重要。嗨,谢谢。但当我仔细观察时,我意识到问题是另外一回事。检查我的问题,我已经编辑过了。