如何随机打印文件中列表中的特定单词

2024-09-30 14:34:30 发布

您现在位置:Python中文网/ 问答频道 /正文

def song():
    print("Wellcome The Song Game")
    newfile = open("songs.txt","r")
    sangg_2D = eval(newfile.read())
    newfile.close()
    sang2 = sangg_2D[0:11]
    print("The Song Name Is", sang2)
    sangg3 = input("Name The Song")
    found = False
    for count in range(len(sangg_2D)):
        if sangg3 == sangg_2D[count][0]:
            score = score + 2
            found = True
            #score = score+2
            print("welldone You Got The Answer Correct On Your First Try")
        else:
            if found==False:
                print("Wrong Answer Try Again")
                song()
song()

它会打印我文件中的每个单词,我只想打印歌曲艺术家和一点名字

The Song Name Is [['j.cole', 'MIDDLE CHILD'], ['Mustard', 'Pure Water'], ['Khalid', 'Talk'], ['Cardi B', 'Please Me'], ['Beyoncé', 'Before I Let Go'], ['Nav', 'Prices On My Head'], ['Chris Brown', 'Back To Love'], ['French Montana', 'Slide'], ['Justin Beiber', 'I Dont Care'], ['Ari Lennox', 'Whipped Cream']]


Tags: thenamefalseifsongiscountscore
1条回答
网友
1楼 · 发布于 2024-09-30 14:34:30

据我所知,根据你的问题和你的源代码,你想采取一首歌的名字,并让用户找到正确的艺术家为该歌曲的名字。如果是这样,那么您可以大大简化代码:

import random

def song():
    score = 0
    print("Wellcome The Song Game")
    newfile = open("songs.txt","r")
    sangg_2D = eval(newfile.read())
    newfile.close()
    randomSong = random.randint(0,len(sangg_2D)-1)
    found = False
    while not found:
        sang2 = sangg_2D[randomSong][1]
        print("The Song Name Is", sang2)
        sangg3 = input("Name The Artist")
        if sangg3 == sangg_2D[randomSong][0]:
            score = score + 2
            found = True
            print("welldone You Got The Answer Correct On Your First Try")
            break
        else:
            print("Wrong Answer Try Again")
song()

首先,读取文件的内容以获取所有艺术家及其各自的歌曲。顺便说一下,使用来自ast模块的ast.literal_eval比使用eval更好。然后从列表中随机挑选一首歌曲,让用户猜出正确的艺术家。如果用户找到了艺术家,那么您的程序就完成了,否则它会再次要求用户猜测艺术家。您还需要在第一次尝试时用score修复该部分,因为没有检查用户是否在第一次尝试时找到它。你知道吗

相关问题 更多 >