0

I am stuck on a bit of code and I can't get it to work.

from random import randint

def random_song():
    global song
    linenum = randint(1,43)
    open('data.txt')
    band_song = readlines."data.txt"(1)
    global band
    band = band_song.readlines(linenum)
    song = band_song.split(" ,")

What I'm trying to do is generate a random number between the 1st and last line of a text file and then read that specific line. Then split the line to 2 strings. Eg: line 26, "Iron Maiden,Phantom of the Opera" split to "Iron Maiden" and then "Phantom of the Opera

Also, how do I split the second string to the first letter of each word and to get that to work for any length and number of letters per word & number of words?

Thank you, MiniBitComputers

  • 2
    You are close, but you need to read about [How to read a file line-by-line into a list](https://stackoverflow.com/questions/3277503/how-to-read-a-file-line-by-line-into-a-list) first. – Yevhen Kuzmovych Feb 03 '20 at 10:21
  • `with open('data.txt') as f: for line in f: line.split(',')` you should start with doing this – Shubham Shaswat Feb 03 '20 at 10:23

1 Answers1

0

There's a space in your split string, you don't need it, just split on ',' and using .strip() to get rid of white space on the outside of the result.

There's some odd code around the reading of the code as well. And you're splitting the list of read lines, not just the line you want to read.

There's also no need for using globals, it's a bad practice and best avoided in almost all cases.

All that fixed:

from random import randint

def random_song():
    with open('data.txt') as f:
        lines = f.readlines()
    artist, song = lines[randint(1,43)].split(',')
    return artist.strip(), song.strip()

print(random_song())

Note that using with ensures the file is closed once the with block ends.

As for getting the first letter of each word:

s = 'This is a bunch of words of varying length.'
first_letters = [word[0] for word in s.split(' ')]
print(first_letters)
Grismar
  • 27,561
  • 4
  • 31
  • 54