2

尽管此填空脚本成功运行,但我不确定如何随机分配空白。可以看出,我在 5-7 之间放置了两个空白。但是,我想随机化它们的设置位置。

sentence = """Immigration is an issue that affects all residents of the United States, regardless of citizenship status"""
sentence0 = sentence.split(" ")
max = len(sentence)
sentence1 = sentence0[0:5]
sentence1 = " ".join(sentence1)
sentence2 = sentence0[7:max]
sentence2 = " ".join(sentence2)
Overall = sentence1 + " _ _ " + sentence2
print(Overall)
test = input()
Overall2 = sentence1 + " " + test + " " + sentence2
print(Overall2)
start = "\033[1m"
end = "\033[0;0m"
if Overall2 == sentence:
    print(start + "Correct" + end)
else:
    print(start + "Incorrect" + end)
4

3 回答 3

2

这很简单并且有效:

import random

sentence = "Immigration is an issue that affects all residents of the United States, regardless of citizenship status"
words = sentence.split(" ")
#SELECT RANDOM WORD FOR PLACING BLANK
rand_index = random.randint(0, len(words)-1)
#KEEP A BACKUP OF THE WORD
word_blanked = words[rand_index]
#REPLACE WORD WITH BLANK
words[rand_index] = "_____"
#MAKE BLANKED SENTENCE AND CORRECT ANSWER
blanked_sentence = ""
correct_answer = ""
for word in words:
    blanked_sentence = blanked_sentence + word + " "
    if word == "_____":
        correct_answer = correct_answer + word_blanked + " "
    else:
        correct_answer = correct_answer + word + " "

print(blanked_sentence)     
answer = input("Enter your answer : ")
if answer == word_blanked:
    print("Correct Answer!")
else:
    print("Wrong Answer!")
    print("Correct Answer is : ")
    print(correct_answer)
于 2021-01-04T18:36:02.773 回答
2

像这样的东西:


import random


sentence = """Immigration is an issue that affects all residents of the United States, regardless of citizenship status"""
sentence0 = sentence.split(" ")

# removed overlap with "max" 
max_length = len(sentence0)

# generate a random slice based on the length of the sentence. 
random_slice = random.randrange(0, max_length)
sentence1 = sentence0[0:random_slice ]
sentence1 = " ".join(sentence1)

# increment two words forward from the random slice
sentence2 = sentence0[random_slice + 2: max_length]
sentence2 = " ".join(sentence2)
Overall = sentence1 + " _ _ " + sentence2
print(Overall)
test = input()
Overall2 = sentence1 + " " + test + " " + sentence2
print(Overall2)
start = "\033[1m"
end = "\033[0;0m"
if Overall2 == sentence:
    print(start + "Correct" + end)
else:
    print(start + "Incorrect" + end)

于 2021-01-04T17:58:23.397 回答
1

通用示例:

import random

sentence = 'The quick brown fox jumps over the lazy dog'

# convert sentence from string to list
sentenceList = sentence.split(' ')

# get random location of the element to be replaced
locToReplace = random.randrange(0, len(sentenceList))

# replace with blanks
sentenceList[locToReplace] = '_ _' 

# convert back to string
updatedSentence = ' '.join(sentenceList)

print(updatedSentence)
于 2021-01-04T18:54:10.697 回答