无限循环不会破坏嵌套for循环

时间:2017-01-05 16:07:24

标签: python for-loop while-loop nested fuzzy-search

我为长度而道歉,我确定这是一个简单的问题。

我正在使用fuzzysearch和Pyenchant模块进行单词搜索。

我正在尝试将嵌套的for循环方法转换为使用for和while循环的方法。我失败了,得到一个无限循环。

基本方法如下

  

对于句子中的单词,检查某个词典中是否存在单词。

     

如果该单词不存在,请使用附魔生成单词建议。

     

对于每个建议,计算生成的单词与原始单词之间的相似度。

     

如果比率足够高,请停止生成建议,并将新单词添加到列表中。

     

对句子中的所有单词执行此操作

例如,对于字符串:A = 'A lvels in Mths and Histtory

输出将是:['A','levels','in','maths','and','history']

我已设法通过以下方式使其工作:

# Imports:
from fuzzywuzzy import fuzz
import enchant
from enchant.tokenize import get_tokenizer
tknzr = get_tokenizer("en")
d = enchant.Dict("en")

A = 'A lvels in Mths and Histtory'

B = []

# Loop through all words in A
for word, position in tknzr(A):

    # Does word exist in Dictionary?
    if d.check(word) is False:

        # generate a suggestion and calculate the 'fuzz factor'
        for suggestion in d.suggest(word):
            ratio = fuzz.ratio(suggestion, word)

            # If ratio is high enough, add word to list B and move to next word in sentence
            if ratio > 75:
                B.append(suggestion)
                break

# If word is in dictionary, just add
    else:
        B.append(word)

Out >>> ['A','levels','in','maths','and','history']

到目前为止很好。

我想将上面的内容转换为使用while和for循环的内容。这将是以下形式:生成新单词,直到达到某个阈值。

我尝试了以下内容:

for word,position in tknzr(A):

    if d.check(word) is False:

        ratio = 0
        while ratio <= 75:

            for suggestion in d.suggest(word):

                print "Suggestion: ", suggestion
                ratio = fuzz.ratio(suggestion, word)

                B.append(word)
    else:
        B.append(word)

然而,这给了我一个关于单词历史的无限循环建议。

Out >>> Suggestion:  History
Out >>> Suggestion:  Historicity
Out >>> Suggestion:  Historic
Out >>> Suggestion:  Historian
Out >>> Suggestion:  Sophistry
Out >>> Suggestion:  Histrionic
Out >>> Suggestion:  Histogram
Out >>> The above forever

问题如下:

for suggestion in d.suggest(word):循环将始终运行完成,之前较高的while循环可以检查比率值。

这意味着检查的最终ratio值是建议的最后一个单词的值。对于Histtory,它是HisstoryHistogram的比率。由于这是<75,while循环条件仍然是真的,因此永远重复。我不能为我的生活,弄清楚如何解决它。

如何更改此代码以使其像第一个示例一样工作? 我应该补充一点:我的目标是速度:我将评估数百万句话。

非常感谢您的阅读。

0 个答案:

没有答案