Using random.choice to print two words from a random line in a file
I'm currently making a music quiz game and I'm trying to select a random line and print the 2 variables I've already assigned in that line, however I can't find a good way to do this. Bellow you can see what I've done so far along with how linked 2 variables per line in the file. Thanks for any help!
This is how I'm adding variables to the different lines
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()
This Is the bit I'm stuck with
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()
What I want is for the program to output the first letter of a song and the Artist associated with the song from a random line of the file
python
New contributor
add a comment |
I'm currently making a music quiz game and I'm trying to select a random line and print the 2 variables I've already assigned in that line, however I can't find a good way to do this. Bellow you can see what I've done so far along with how linked 2 variables per line in the file. Thanks for any help!
This is how I'm adding variables to the different lines
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()
This Is the bit I'm stuck with
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()
What I want is for the program to output the first letter of a song and the Artist associated with the song from a random line of the file
python
New contributor
1
You have lines likeCold Play Clocks
in your file. How can you determine if it's notCold
andPlay Clocks
?
– iBug
Dec 27 at 14:41
1
You representation in the file is bad: how do you - only using the created file - distinguish between artists that have a 2 names and 1 name titles (Pharrel Williams Happy
) and those that have 1 name and 2 word titles (Coldplay The Scientist
) ?
– Patrick Artner
Dec 27 at 14:42
Also: do not use ; in pyhton code - read python.org/dev/peps/pep-0008 for more infos
– Patrick Artner
Dec 27 at 14:43
Also: thisSong = (random.choice(open("SongFile2.txt").read().split()))
does not respect song titles or artists at all - it might give you an artist name
– Patrick Artner
Dec 27 at 14:44
add a comment |
I'm currently making a music quiz game and I'm trying to select a random line and print the 2 variables I've already assigned in that line, however I can't find a good way to do this. Bellow you can see what I've done so far along with how linked 2 variables per line in the file. Thanks for any help!
This is how I'm adding variables to the different lines
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()
This Is the bit I'm stuck with
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()
What I want is for the program to output the first letter of a song and the Artist associated with the song from a random line of the file
python
New contributor
I'm currently making a music quiz game and I'm trying to select a random line and print the 2 variables I've already assigned in that line, however I can't find a good way to do this. Bellow you can see what I've done so far along with how linked 2 variables per line in the file. Thanks for any help!
This is how I'm adding variables to the different lines
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()
This Is the bit I'm stuck with
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()
What I want is for the program to output the first letter of a song and the Artist associated with the song from a random line of the file
python
python
New contributor
New contributor
New contributor
asked Dec 27 at 14:34
Aaryan Shenoy
31
31
New contributor
New contributor
1
You have lines likeCold Play Clocks
in your file. How can you determine if it's notCold
andPlay Clocks
?
– iBug
Dec 27 at 14:41
1
You representation in the file is bad: how do you - only using the created file - distinguish between artists that have a 2 names and 1 name titles (Pharrel Williams Happy
) and those that have 1 name and 2 word titles (Coldplay The Scientist
) ?
– Patrick Artner
Dec 27 at 14:42
Also: do not use ; in pyhton code - read python.org/dev/peps/pep-0008 for more infos
– Patrick Artner
Dec 27 at 14:43
Also: thisSong = (random.choice(open("SongFile2.txt").read().split()))
does not respect song titles or artists at all - it might give you an artist name
– Patrick Artner
Dec 27 at 14:44
add a comment |
1
You have lines likeCold Play Clocks
in your file. How can you determine if it's notCold
andPlay Clocks
?
– iBug
Dec 27 at 14:41
1
You representation in the file is bad: how do you - only using the created file - distinguish between artists that have a 2 names and 1 name titles (Pharrel Williams Happy
) and those that have 1 name and 2 word titles (Coldplay The Scientist
) ?
– Patrick Artner
Dec 27 at 14:42
Also: do not use ; in pyhton code - read python.org/dev/peps/pep-0008 for more infos
– Patrick Artner
Dec 27 at 14:43
Also: thisSong = (random.choice(open("SongFile2.txt").read().split()))
does not respect song titles or artists at all - it might give you an artist name
– Patrick Artner
Dec 27 at 14:44
1
1
You have lines like
Cold Play Clocks
in your file. How can you determine if it's not Cold
and Play Clocks
?– iBug
Dec 27 at 14:41
You have lines like
Cold Play Clocks
in your file. How can you determine if it's not Cold
and Play Clocks
?– iBug
Dec 27 at 14:41
1
1
You representation in the file is bad: how do you - only using the created file - distinguish between artists that have a 2 names and 1 name titles (
Pharrel Williams Happy
) and those that have 1 name and 2 word titles (Coldplay The Scientist
) ?– Patrick Artner
Dec 27 at 14:42
You representation in the file is bad: how do you - only using the created file - distinguish between artists that have a 2 names and 1 name titles (
Pharrel Williams Happy
) and those that have 1 name and 2 word titles (Coldplay The Scientist
) ?– Patrick Artner
Dec 27 at 14:42
Also: do not use ; in pyhton code - read python.org/dev/peps/pep-0008 for more infos
– Patrick Artner
Dec 27 at 14:43
Also: do not use ; in pyhton code - read python.org/dev/peps/pep-0008 for more infos
– Patrick Artner
Dec 27 at 14:43
Also: this
Song = (random.choice(open("SongFile2.txt").read().split()))
does not respect song titles or artists at all - it might give you an artist name– Patrick Artner
Dec 27 at 14:44
Also: this
Song = (random.choice(open("SongFile2.txt").read().split()))
does not respect song titles or artists at all - it might give you an artist name– Patrick Artner
Dec 27 at 14:44
add a comment |
3 Answers
3
active
oldest
votes
You should switch the way to store your data - use a seperator character between artist and song that does not occur in either one.
A '|'
is a good divider for songs and artists. You can use it like so:
Write data file:
# 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
Game:
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))
Output:
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'
....
add a comment |
The read()
method returns the entire file contents as one long string, which makes it harder to pick out a random song. Try using readlines()
instead, which returns each line in the file in a list, making it much easier to use random.choice()
.
And as others have said, using a space to separate the artist and song title makes it much harder to tell where the artist name ends and the song title begins, because the artist and song title can also contain spaces.
add a comment |
You could do something like this to get a random line:
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]
When you get the random line use regular expressions to get the desired elements. This is a useful site to test your regular expression:
https://regex101.com/
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Aaryan Shenoy is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53946701%2fusing-random-choice-to-print-two-words-from-a-random-line-in-a-file%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
3 Answers
3
active
oldest
votes
3 Answers
3
active
oldest
votes
active
oldest
votes
active
oldest
votes
You should switch the way to store your data - use a seperator character between artist and song that does not occur in either one.
A '|'
is a good divider for songs and artists. You can use it like so:
Write data file:
# 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
Game:
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))
Output:
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'
....
add a comment |
You should switch the way to store your data - use a seperator character between artist and song that does not occur in either one.
A '|'
is a good divider for songs and artists. You can use it like so:
Write data file:
# 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
Game:
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))
Output:
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'
....
add a comment |
You should switch the way to store your data - use a seperator character between artist and song that does not occur in either one.
A '|'
is a good divider for songs and artists. You can use it like so:
Write data file:
# 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
Game:
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))
Output:
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'
....
You should switch the way to store your data - use a seperator character between artist and song that does not occur in either one.
A '|'
is a good divider for songs and artists. You can use it like so:
Write data file:
# 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
Game:
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))
Output:
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'
....
answered Dec 27 at 15:04
Patrick Artner
21k52142
21k52142
add a comment |
add a comment |
The read()
method returns the entire file contents as one long string, which makes it harder to pick out a random song. Try using readlines()
instead, which returns each line in the file in a list, making it much easier to use random.choice()
.
And as others have said, using a space to separate the artist and song title makes it much harder to tell where the artist name ends and the song title begins, because the artist and song title can also contain spaces.
add a comment |
The read()
method returns the entire file contents as one long string, which makes it harder to pick out a random song. Try using readlines()
instead, which returns each line in the file in a list, making it much easier to use random.choice()
.
And as others have said, using a space to separate the artist and song title makes it much harder to tell where the artist name ends and the song title begins, because the artist and song title can also contain spaces.
add a comment |
The read()
method returns the entire file contents as one long string, which makes it harder to pick out a random song. Try using readlines()
instead, which returns each line in the file in a list, making it much easier to use random.choice()
.
And as others have said, using a space to separate the artist and song title makes it much harder to tell where the artist name ends and the song title begins, because the artist and song title can also contain spaces.
The read()
method returns the entire file contents as one long string, which makes it harder to pick out a random song. Try using readlines()
instead, which returns each line in the file in a list, making it much easier to use random.choice()
.
And as others have said, using a space to separate the artist and song title makes it much harder to tell where the artist name ends and the song title begins, because the artist and song title can also contain spaces.
answered Dec 27 at 14:47
John Gordon
9,50551728
9,50551728
add a comment |
add a comment |
You could do something like this to get a random line:
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]
When you get the random line use regular expressions to get the desired elements. This is a useful site to test your regular expression:
https://regex101.com/
add a comment |
You could do something like this to get a random line:
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]
When you get the random line use regular expressions to get the desired elements. This is a useful site to test your regular expression:
https://regex101.com/
add a comment |
You could do something like this to get a random line:
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]
When you get the random line use regular expressions to get the desired elements. This is a useful site to test your regular expression:
https://regex101.com/
You could do something like this to get a random line:
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]
When you get the random line use regular expressions to get the desired elements. This is a useful site to test your regular expression:
https://regex101.com/
answered Dec 27 at 14:51
Amuoeba
457
457
add a comment |
add a comment |
Aaryan Shenoy is a new contributor. Be nice, and check out our Code of Conduct.
Aaryan Shenoy is a new contributor. Be nice, and check out our Code of Conduct.
Aaryan Shenoy is a new contributor. Be nice, and check out our Code of Conduct.
Aaryan Shenoy is a new contributor. Be nice, and check out our Code of Conduct.
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53946701%2fusing-random-choice-to-print-two-words-from-a-random-line-in-a-file%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
1
You have lines like
Cold Play Clocks
in your file. How can you determine if it's notCold
andPlay Clocks
?– iBug
Dec 27 at 14:41
1
You representation in the file is bad: how do you - only using the created file - distinguish between artists that have a 2 names and 1 name titles (
Pharrel Williams Happy
) and those that have 1 name and 2 word titles (Coldplay The Scientist
) ?– Patrick Artner
Dec 27 at 14:42
Also: do not use ; in pyhton code - read python.org/dev/peps/pep-0008 for more infos
– Patrick Artner
Dec 27 at 14:43
Also: this
Song = (random.choice(open("SongFile2.txt").read().split()))
does not respect song titles or artists at all - it might give you an artist name– Patrick Artner
Dec 27 at 14:44