2014-01-19 50 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

    謝謝,它也不會打印定義。它只是要求拼寫 –