使用自定义模块检查字符串中所有可能的单词组合的语法

Checking grammar using a custom module for all possible combinations of words in string

我正在为一所学校开发一个软件,学生可以在其中实际输入句子,然后检查他们的语法,但是他们会得到随机的单词组合,例如

    The brown quick fox fence over jumped the

由此他们必须弄清楚句子并用正确的语法重写句子。当他们的答案错误时,我希望程序为所有可能的组合重新排列句子,然后检查每个可能组合的语法。

为了获得我使用的句子的随机排列,

    text = raw_input("You:")
    #shuffling for all possibilities
    def randm(text):
          text = text.split(" ")
          for i in itertools.permutations(text): 
                    rnd_text = " ".join(i) 

然后我有自己的模块来检查语法,

    engrammar.grammar_cache(rnd_text)

当rnd_text作为上述方法的参数传递时,如果语法正确,则重新排列的文本将以正确的语法显示。那么我如何一次将 "for loop" 的单个输出 传递到我必须检查所有可能输出的语法的方法?

一种方法是将您的函数变成生成器。

def randm(text):
      text = text.split(" ")
      for i in itertools.permutations(text): 
                yield " ".join(i)

那么你所要做的就是

for word in randm(text):
    engrammar.grammar_cache(word)

您可以阅读有关生成器的更多信息here

如果您不想使用生成器,您总是可以从您的函数中return一个列表,然后遍历该列表。

def randm(text):
      words = []
      text = text.split(" ")
      for i in itertools.permutations(text): 
                words.append(" ".join(i))
      return words

words = randm(text)
for word in words:
    engrammar.grammar_cache(word)