Моя музыкальная викторина берет список песен из внешнего файла с именем «Songs.txt» и берет первую букву каждого слова в одной песне (из 7, выбранных случайным образом), а затем отображает исполнителя этой песни. Затем у пользователя есть два предположения, и затем начисляются соответствующие баллы:
# MUSIC QUIZ GAME
import random
# Import the 'random' function in order to select a random number and get a random song.
import time
# Importing the ability to 'pause' to give the program a more professional feel.
import sys
# Import the ability to close the program.
import linecache
# Import the ability to get a specific line from a file.
userscore = 0
# The userscore is automatically zero, because they have just started playing.
random_picker = random.randint(1,7)
# Using the random operator, we pick a random number from 1 to 5, because there are 5 songs. We will use this to select the same random line from two files.
# ----- Accessing the Songs database ----- #
# Open the file.
file = open("Songs.txt", "r")
# Get the line from file. The line number is determined by the 'random_picker' used earlier.
song = linecache.getline(r"Songs.txt", random_picker).upper()
# Split the line into individual words.
song_prompt = song.split()
# ----- Accessing the Artists database ----- #
file = open("Artists.txt", "r")
artist = linecache.getline(r"Artists.txt", random_picker)
# -----Giving the user the prompt ----- #
print("\nYour prompt is: ")
# Get only the first letter of each word in the prompt, then output them.
for word in song_prompt:
print(word[0])
print("by " + artist)
guess1 = input("Enter your song name guess:\n")
if guess1 == song:
print("Well done!")
userscore = userscore + 3
print("Your score is " + str(userscore) + ".")
elif guess1 != song:
print("Wrong guess.")
guess2 = input("What is your second guess for the song name?\n")
if guess2 == song:
print("Well done.")
userscore = userscore + 1
print("Your score is " + str(userscore) + ".")
else:
print("You have gotten both guesses wrong.")
sys.exit()
Однако при обоих предположениях, с правильной песней, заглавными буквами, строчными буквами, заголовками с заглавными буквами и т. д., Программное обеспечение всегда считает ответ неправильным. Это связано с тем, как файл читается? Я не совсем уверен. Если бы кто-нибудь мог помочь мне с этим вопросом, это было бы очень признательно.
Файл Songs.txt содержит этот список:
Let It Happen
New Gold
Shotgun
Metamodernity
Bad Guy
Blank Space
Bohemian Rhapsody
Файл Artists.txt содержит этот список:
Tame Impala
Gorillaz
George Ezra
Vansire
Billie Eillish
Taylor Swift
Queen
Например, в викторине говорится:
Your prompt is:
N
G
by Gorillaz
Enter your song name guess:
New Gold
Wrong guess.
What is your second guess for the song name?
NEW GOLD
You have gotten both guesses wrong.
Я ожидаю получить правильный ответ.
Я думаю, у вас также может быть проблема с тем, как вы читаете файлы .txt.
Когда вы запускаете следующую строку: song = linecache.getline(r"Songs.txt", random_picker).upper()
Значение, присвоенное song, будет примерно таким 'LET IT HAPPEN\n'
Чтобы избежать этого, вы можете использовать метод .rstrip():
song = linecache.getline(r"Songs.txt", random_picker).upper().rstrip('\n')
Привет, трим, спасибо за ваш комментарий. Я реализовал этот метод чтения, и он отлично работает. Спасибо.
Строки песен по-прежнему заканчиваются новыми строками? то есть == song.strip()