使用random.choice从文件的随机行中打印两个单词

时间:2018-12-27 14:34:28

标签: python

我当前正在做一个音乐问答游戏,我试图选择一个随机行并打印我已经在该行中分配的2个变量,但是我找不到一种很好的方法来实现。在下面,您可以看到我到目前为止所做的事情以及文件中每行如何链接2个变量。感谢您的帮助!

这就是我将变量添加到不同行的方式

    Artist='Cold Play';Song1='Clocks'
    file.write(Artist + " " + Song1 + "\n")


    Artist='Beatles';Song1='Revolution'
    file.write(Artist + " " + Song1 + "\n")


    Artist='Pharrel Williams';Song1='Happy'
    file.write(Artist + " " + Song1 + "\n")


    Artist='Owl City';Song1='Fireflies'
    file.write(Artist + " " + Song1 + "\n")


    Artist='Oasis';Song1='Wonderwall'
    file.write(Artist + " " + Song1 + "\n")

    file.close()

这就是我坚持的地方

    Song = (random.choice(open("SongFile2.txt").read().split()))



    print("Please type yes to continue playing")
    print("or type something random to recieve a nice message and quit the 
    game")

    PlayerAnswer = input()

    if PlayerAnswer == ("yes"):


       print("Question:" + str(Question))

       print("" + Song1[0] + ": This is the first letter of the song" )
       print("The Artist is: " + Artist)


       print("Now guess the Song (Remember to use capital letters for 
       Names)")

       PlayerGuess = input()

我想要的是程序从文件的随机行中输出歌曲的首字母和与歌曲相关的艺术家

3 个答案:

答案 0 :(得分:0)

read()方法将整个文件内容作为一个长字符串返回,这使得挑选随机歌曲变得更加困难。尝试改用readlines(),它返回列表中文件的每一行,使使用random.choice()更加容易。

就像其他人所说的那样,使用空格将歌手和歌曲名称分开会使得很难分辨歌手名称和歌曲名称的开头,因为歌手和歌曲名称也可以包含空格。

答案 1 :(得分:0)

您可以执行以下操作以获取随机行:

import random

with open("file.txt","r") as f:
    list_of_lines = f.readlines()
    list_of_indexes = list(range(len(list_of_lines)))

    rand_index = random.choice(list_of_indexes)
    random_line = list_of_lines[rand_index]

当您获得随机线时,请使用正则表达式来获取所需的元素。这是测试您的正则表达式的有用站点: https://regex101.com/

答案 2 :(得分:0)

您应该切换存储数据的方式-在歌手和歌曲之间使用分隔符,而这两者都不出现。

# use a seperator character between artist and song that does not occur in either with open("songs.txt","w") as f: f.write('''Cold Play|Clocks Beatles|Revolution Pharrel Williams|Happy Owl City|Fireflies Oasis|Wonderwall''') # write a multiline-file 是歌曲和艺术家的良好分隔物。您可以像这样使用它:

写入数据文件:

import random

def get_all_music():
    """Load music from songs.txt and return as list of 2-elem-lists.
    Lines not containing | are ignored."""
    with open("songs.txt") as f:
        return [x.strip().split("|") for x in f.readlines() if '|' in x]

all_music = get_all_music()

for _ in range(3):
    artist, song = random.choice(all_music)
    print("Song starting with '{}' by '{}'.".format(song[0],artist))
    s = input("What is it's name?")
    if s == song:
        print("Correct!")
    else:
        print("'{}' is wrong. It was '{}'".format(s,song))

游戏:

Song starting with 'C' by 'Cold Play'.
What is it's name? Clocks
Correct!
Song starting with 'F' by 'Owl City'.
What is it's name? Clocks
'Clocks' is wrong. It was 'Fireflies'
....

输出:

{{1}}