2014-01-19 49 views
2

大家好,这是我的第一篇文章,我只编了一个星期左右,我的学校老师也不是最擅长解释的东西,所以很好:)我试图编写一个程序这将显示一个单词的定义,然后用户将输入他们认为该单词是什么。如果他们得到它的权利,他们将被授予2分,如果他们得到1个字母错误,那么他们将被给予1分,如果超过1信是错误的,那么他们会得到0分。在将来用户将不得不登录,但我正在这部分首先工作。任何想法如何让这个工作?Python - 拼写测试

score = score 
definition1 = "the round red or green fruit grown on a tree and used in pies" 
word1 = "apple" 
def spellingtest(): 
    print (definition1) 
spellinginput = input ("enter spelling") 
if spellinginput == word1 
    print = ("Well done, you have entered spelling correctly") and score = score+100 

编辑:当我运行它,我得到一个无效的语法错误在这条线

if spellinginput == word1 
+2

什么问题? – martineau

+1

如果您可以提出更详细的问题,您会得到更好的回复。当你运行代码时会发生什么,结果与你期望的结果有什么不同? –

+0

我已经编辑了一下 –

回答

0

如果他们得到它的权利,他们将获得2分,如果他们得到1个 信错那么他们会得到1分,如果超过1个字母 是错误的,那么他们将被给予0分。

这并不像您想象的那么简单。单错误的拼写将意味着,单个字符apple -> appple

  • 单个字符的删除apple -> aple
  • 更换单个字符apple - apqle
  • 而不是编写自己的算法的

    1. 插入把所有这些,你需要卸载任务给专家difflib.SequenceMatcher.get_opcode

      它解除rmines,将一个字符串转换为另一个字符串所需的更改,而您的Job是了解和分析操作码,并确定转换次数是否超过1。

      实施

      misspelled = ["aple", "apqle", "appple","ale", "aplpe", "apppple"] 
      from difflib import SequenceMatcher 
      word1 = "apple" 
      def check_spelling(word, mistake): 
          sm = SequenceMatcher(None, word, mistake) 
          opcode = sm.get_opcodes() 
          if len(opcode) > 3: 
           return False 
          if len(opcode) == 3: 
           tag, i1, i2, j1, j2 = opcode[1] 
           if tag == 'delete': 
            if i2 - i1 > 1: 
             return False 
           else: 
            if j2 - j1 > 1: 
             return False 
          return True 
      

      输出

      for word in misspelled : 
          print "{} - {} -> {}".format(word1, word, check_spelling(word1, word)) 
      
      
      apple - aple -> True 
      apple - apqle -> True 
      apple - appple -> True 
      apple - ale -> False 
      apple - aplpe -> False 
      apple - apppple -> False 
      
    +0

    也许代替Levenshtein,也考虑到将两个相邻的字母换成一个单一的错误。 – Hyperboreus

    +0

    谢谢,请记住,我是新的,如果我接受我的课程,我会如何使它打印出“如果输入与正确的拼写相匹配”以及“错误的拼写”是正确的拼写...“如果不匹配 –

    0

    好吧,如果你想保持它的简单,

    • 你的第一行:

      score = score

    不知道你要实现有什么,你应该初始化为零:

    score = 0 
    
    • 在你if声明

      if spellinginput == word1

    你在最后有一个遗漏冒号。

    • 你的功能

      def spellingtest():

    应该打印的定义,但它永远不会被调用。此外,它使用了一个不鼓励的全局变量。它应该是

    def spellingtest (definition): 
        print (definition) 
    

    然后,你需要调用它

    spellingtest(definition1) 
    
    • 最后一行

      print = ("Well done, you have entered spelling correctly") and score = score+100

    ,如果你要打印的那句话,然后增加你应该记的分数伊特

    print ("Well done, you have entered spelling correctly") 
    score = score + 100 
    

    否则你正试图重新定义print这是一个保留关键字。而and用于布尔操作AND,而不是创建一系列语句。

    +0

    谢谢,现在我得到分数没有定义 –

    +0

    谢谢,它也不会打印定义。它只是要求拼写 –