Reading a text file and showing only part of it some of it in python

101 Views Asked by At

So I'm creating a code in python 3.3 where you have to guess a song with only the first letter of the song and artist so I formatted my text file like this:

Domo23-Tyler The Creator
Happy hour-The Housemartins
Charming Man-The Smiths
Toaster-Slowthai
Two time-Jack Stauber
etc...

So I was trying to work out a way to print this but only showing the first letter of each word in the song name and the whole artist name like this:

C M-The Smiths

Justwondering if anyone could help

2

There are 2 best solutions below

7
Wector On

If your songs are stored let's say in "songs.txt" here is my solution:

import random

# Without the "with as" statement"
f = open("songs.txt", "r")
list_of_songs = []
text_of_songs = f.read()
#Closing the file - Thank you @destoralater
f.close()
for song in text_of_songs.split("\n"):
    list_of_songs.append(song)

def get_random_song_clue(list_of_songs):
    song = random.choice(list_of_songs)
    title, artis = song.split("-")
    title_clue = " ".join([letter[0] for letter in title.split(" ")])
    return f"{title_clue}-{artis}"

print(get_random_song_clue(list_of_songs))

One random Output:

D-Tyler The Creator
2
butterflyknife On

Supposing your data is in a list, like so:

data = ["Domo23-Tyler The Creator",
    "Happy hour-The Housemartins",
    "Charming Man-The Smiths",
    "Toaster-Slowthai",
    "Two time-Jack Stauber"]

I'll build up the final code for you step by step.

  1. Extract the song name by first splitting each data item at the "-", eg: data[2].split("-")[0].

  2. Split the song name at the spaces to get a list of the words in the song name: data[2].split("-")[0].split(" ").

  3. List comprehension to only keep the first letter of each word: [word[0] for word in data[2].split("-")[0].split(" ")]

  4. Now concatenate that last list of letters: " ".join([word[0] for word in data[2].split("-")[0].split(" ")])

  5. Add in the name of the artist: " ".join([word[0] for word in data[2].split("-")[0].split(" ")]) + "-" + data[2].split("-")[1]

Now finalise by doing the whole lot with another list comprehension. I've used a lambda function for cleanness.

hide_name = lambda song_record: \
                    " ".join([word[0] for word in song_record.split("-")[0].split(" ")]) \
                    + "-" + song_record.split("-")[1]

[hide_name(record) for record in data]

Output for the list given above:

['D-Tyler The Creator',
 'H h-The Housemartins',
 'C M-The Smiths',
 'T-Slowthai',
 'T t-Jack Stauber']

Edit: remember that this depends on your song records having precisely one "-" in them, which delimits the song name and artist. If either the song name or artist contains a hyphen, you'll get unexpected behaviour.