Music Quiz Project - PullRequest
       35

Music Quiz Project

0 голосов
/ 31 декабря 2018

Я создаю музыкальную викторину.Ниже мой файл CSV.Я хотел бы выбрать песню и исполнителя в произвольном порядке из файла - отображая имя исполнителя, но отображая только ПЕРВУЮ БУКВУ каждого слова в названии песни.

Мне было интересно, знает ли кто-нибудь из вас, как я могу сделать это на Python.Имя файла называется playlist.csv

Я пробовал несколько различных методов, таких как приведенный ниже, но он не работает.

with open('playlist.csv') as mycsv:
    print(mycsv.readline()[0]) 

Я уже импортировал файл CSV и сохранилисполнители и песни в CSV-файле.

Songs                                     Artists

Maroon 5 Girls Like You                   Andrea Garcia 
I Like It                                 Cardi B   
God's Plan                                Drake 
No Tears Left To Cry                      Ariana Grande 
Psycho                                    Post Malone   
The Middle                                Maren Morris  
Better Now                                Post Malone   
In My Feelings                            Drake 
It's Coming Home                          The Lightning Seeds   
One Kiss                                  Dua Lipa  

Произвольная песня и исполнитель выбраны.

Например:

M, Andrea Garcia

G, Drake

B, Post Malone

O, Dua Lipa.

В данный момент я также пытаюсь создать оператор if, в котором, если предположение пользователя о случайно сгенерированной песне верное, он получает сообщение о том, что"Правильный ответ".Это то, что я пытался сделать в данный момент.

    userName = str
    password = str
    userName = raw_input("What is your name?")
    password = raw_input("Please enter the correct password.")

if userName == "John" or "John" or password!= "musicquiz":
    print("Sorry, the username is taken and/or the password is incorrect.")
    quit()

if userName!= "John" and password == "musicquiz":
    print("Hello", userName, "welcome to the game!")

import random
with open('playlist.csv') as mycsv:
    f=mycsv.readlines()[1:]
    random_line=random.choice(f).split(',')
    print(random_line[0][0],",",random_line[3])

userGuess = str
userScore = int
userScore = 0

userGuess = raw_input("What is the correct name of this song?")

if userGuess == true:
    print("Well done, that was the correct answer. You have scored three points")
    userScore + 3

else:
    print("Sorry, your guess was incorrect. You have one more chance to guess it right")
    raw_input("What is the correct name of this song?")

if userGuess != true:
    print("Sorry, game over.")
    quit()

if userGuess == true:
    print("Well done, that was the correct answer. You scored one point.")
    userScore + 1

Ответы [ 2 ]

0 голосов
/ 06 февраля 2019

Я ждал несколько недель, чтобы дать вам ответ, чтобы вы не смогли завершить себя, что очень похоже на домашнее задание

Итак, прежде всего, ваш входной файл:

playlist.csv

Songs,Artists
Maroon 5 Girls Like You,Andrea Garcia 
I Like It,Cardi B
God's Plan,Drake 
No Tears Left To Cry,Ariana Grande 
Psycho,Post Malone
The Middle,Maren Morris
Better Now,Post Malone
In My Feelings,Drake 
It's Coming Home,The Lightning Seeds
One Kiss,Dua Lipa

и код:

import csv
import random

with open('playlist.csv', 'rb') as input_file:
    csv_source = csv.DictReader(input_file)   
    all_songs_and_artists = list(csv_source)

song_and_artist_chosen = random.choice(all_songs_and_artists)

song_words = song_and_artist_chosen["Songs"].split()
song_initials = "".join(item[0] for item in song_words)
initials_uppercase = song_initials.upper()

print "Welcome to the music quiz"
print "-------------------------"
print "\n"
print "Here's an artist: " + song_and_artist_chosen["Artists"]
print "and the initials of the song we are searching are: " + initials_uppercase
user_guess = raw_input("What is the name of this song? ")

if song_and_artist_chosen["Songs"].upper() == user_guess.upper():
    print "Well done, that was the correct answer."
else:
    print "Sorry, your guess was incorrect. You have one more chance to guess it right"
    user_guess = raw_input("What is the name of this song? ")
    if song_and_artist_chosen["Songs"].upper() == user_guess.upper():
        print "Well done, that was the correct answer."
    else:
        print "Sorry, game over."
0 голосов
/ 01 января 2019
import random
with open('playlist.csv') as mycsv:
    f=mycsv.readlines()[1:] #all except header
    random_line=random.choice(f).split(',')
    print(random_line[0][0],",",random_line[1])

Выход

M , Andrea Garcia

playlist.csv

Songs,Artists
Maroon 5 Girls Like You,Andrea Garcia
I Like It,Cardi B
God's Plan,Drake
No Tears Left To Cry,Ariana Grande
Psycho,Post Malone
The Middle,Maren Morris
Better Now,Post Malone
In My Feelings,Drake
It's Coming Home,The Lightning Seeds
One Kiss,Dua Lipa 
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...