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

2024-04-16 20:47:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一所学校创建一个软件,在那里学生们会输入一个句子,然后他们的语法会被检查,但是他们会被随机的单词组合,比如

    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èu text作为上述方法的参数传递时,如果语法正确,则重新排列的文本将以正确的语法显示。那么,如何从“for循环”中一次传递一个输出给我必须检查所有可能输出的语法的方法呢?


Tags: the方法textfor软件语法quick单词
1条回答
网友
1楼 · 发布于 2024-04-16 20:47:31

一种方法是把你的函数变成一个生成器。你知道吗

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的更多信息。你知道吗

如果您不想使用生成器,您可以从函数返回一个列表,然后遍历该列表。你知道吗

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)

相关问题 更多 >