2

みなさん、こんにちは。これは私の最初の投稿です。コーディングを始めてまだ 1 週間ほどです。学校の先生も説明が下手なので、親切に教えてください :)ユーザーはその単語が正しいと思うものを入力します。正解した場合は 2 ポイントが与えられ、1 文字間違えた場合は 1 ポイントが与えられ、1 文字以上間違っていた場合は与えられた 0 点。将来、ユーザーはログインする必要がありますが、最初にこの部分に取り組んでいます。これを機能させる方法はありますか?

    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
4

2 に答える 2

0

正解すると2点、1文字間違えると1点、1文字以上間違えると0点となります。

あなたが考えているほど単純ではありません。スペルミスが 1 つあると、次のようになります。

  1. 1 文字の挿入apple -> appple
  2. 1文字の削除apple -> aple
  3. 1 文字の置換apple - apqle

これらすべてを取得する独自のアルゴリズムを作成する代わりに、タスクをエキスパートdifflib.SequenceMatcher.get_opcodeにオフロードする必要があります。

ある文字列を別の文字列に変換するために必要な変更を決定します。あなたの仕事は、オペコードを理解して解析し、変換の数が 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
于 2014-01-19T18:25:59.660 に答える
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は、予約済みのキーワードを再定義しようとしています。Andandは、一連のステートメントを作成するためではなく、ブール演算 AND に使用されます。

于 2014-01-19T18:58:12.017 に答える