如何使用外部文件的答案进行测验?

时间:2019-01-17 12:18:48

标签: python variables

我正在尝试进行测验,但我的答案在一个外部文件中,因此,每次我使用正确答案运行它们时,他们都会说这是不正确的。

这是我的代码:

randNum = int(random.randint(0, 4))

song = open("songList.csv","rt")

with open("songList.csv", "rt") as f:

songn = str(song.readlines()[randNum])
reader= csv.reader(f)
for row in reader:
   print (songn[0])

guess = input("What is the song called?")
score = 0
correct_guess = False
while True:
    if guess == songn:
        correct_guess = True
        break

    score += 1
    if score>=total:
        break
    song_guess = input("Incorrect! Try again:\n> ")
if correct_guess:
    print("Answer correct!")
else:
    print("game over")

1 个答案:

答案 0 :(得分:0)

正如注释中指出的,您在其中一个字符串中包含尾随换行符。因此,它们是不相等的。

但是我不只是删除换行符。如果逻辑允许,在测试相等性之前将字符串标准化是一个很好的习惯。您可以做很多事情来规范化:

def normalize(string):
    string = string.strip()  # Remove any leading or trailing whitespaces
    string = string.lower()  # Make all letters lowercase 
    string = " ".join(string.split())  # If the user hit spacebar twice, for example, will remove the double space. Note can have side effects.
    return string 

然后检查

if normalize(string1) == normalize(string2):
    do_something() 

实际上,如果您要处理用户输入,那么这可能还不够。例如,如果用户输入错误,则不会匹配。

所以我还建议您查看Fuzzywuzzy库

from fuzzywuzzy import fuzz 

def similar(string1, string2):
    ratio = fuzz.ratio(string1, string2)
    return ratio >= 85  # number between 0 and 100. Higher means fewer differences are allowed

Fuzzywuzzy非常强大且易于使用。有关更多信息:https://github.com/seatgeek/fuzzywuzzy