首页 > 解决方案 > 从文本文件中选择随机行而不在 Python 中重复

问题描述

我有一个程序可以打印歌曲的首字母和他们的艺术家,你必须猜出这首歌。

我希望随机选择歌曲,但只显示一次,并且我希望游戏在列表中的所有歌曲都显示后结束。

这是我的文本文件“songs.txt”的示例:

Billie Eilish - 派对结束时
Ariana Grande - 男友
TMC - No Scrubs
Destiny's Child - Say My Name
Adele - Hello
Katy Perry - California Girls
BTS - Home

这是我的输出:

The first letter of the song is: H and the artist is: BTS

这是我的代码:

   import random
   def random_line(songs):
       lines = open(songs).read().splitlines()
       return random.choice(lines)
   random =(random_line('songs.txt'))
   artist = (random.split(' - ')[0])
   song = (random.split(' - ',1)[1])
   song_letter = song[0]
   print ("The first letter of the song is: " + song_letter + " and the artist is: " + artist) 

标签: pythonloopsfilerandomrepeat

解决方案


我假设您将在某种 while 或 for 循环中运行它,并且可能需要根据实际存储的输入评估用户输入。因此,您可能希望在函数中包含回归艺术家 song_letter。你没有收到第一个字母,因为你没有足够远地索引歌曲

import random

"""I've used a list of the songs you provided but you may wish to import these from a txt file and then convert to a list"""

songs = ['Billie Eilish - When The Party Is Over',
         'Ariana Grande - boyfriend',
        'TMC - No Scrubs',
        "Destiny's Child - Say My Name",
        "Adele - Hello",
        "Katy Perry - California Girls",
        "BTS - Home"]



def artist_song(song):
    artist = song.split(' - ')[0]
    song_letter = song.split(' - ')[1][0]
    print ("The first letter of the song is: " + song_letter + " and the artist is: " + artist)

    """You may chose to use return (artist,song_letter) insteas so you can use them for comparision"""

song = random.choice(songs) 
artist, song_letter = artist_song(song)
songs.remove(song)

您可能希望多次执行此操作,直到不再有任何歌曲,您可以按以下方式执行此操作:


while songs:
    song = random.choice(songs) 
    artist, song_letter = artist_song(song)
    x = input('User input here: ').lower()
    if x == song.split(' - ')[1].lower():
        """What to do if their input matches"""
        pass
    else:
        """What to do if the song is wrong"""
        pass
    songs.remove(song)

对于输入,请考虑其他因素,例如输入验证,因此请确保用户输入只有字母,没有数字/空格等。您可以包括一个计数器来跟踪分数。


推荐阅读