读取文本文件并仅在python中显示其中的一部分

问题描述

所以我要在 python 3.3 中创建代码在这里您必须猜一首只有歌曲和歌手首字母的歌曲,所以我将文本文件的格式设置为:

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

因此,我试图找出一种打印方法,但是只显示歌曲名称中每个单词的首字母和整个歌手姓名,如下所示:

C M-The Smiths

怀疑是否有人可以帮助

解决方法

如果存储了您的歌曲,那么在“ songs.txt”中说这是我的解决方法:

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))

一个随机输出:

D-Tyler The Creator
,

假设您的数据在列表中,如下所示:

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

我将逐步为您构建最终代码。

  1. 通过首先在“-”处分割每个数据项来提取歌曲名称,例如:data[2].split("-")[0]

  2. 在空格处分割歌曲名称,以获取歌曲名称中的单词列表:data[2].split("-")[0].split(" ")

  3. 列表理解仅保留每个单词的第一个字母:[word[0] for word in data[2].split("-")[0].split(" ")]

  4. 现在将最后一个字母列表连接起来:" ".join([word[0] for word in data[2].split("-")[0].split(" ")])

  5. 添加艺术家的名字:" ".join([word[0] for word in data[2].split("-")[0].split(" ")]) + "-" + data[2].split("-")[1]

现在通过对列表的另一遍理解完成全部工作。我使用了lambda函数进行清洁。

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]

上面给出的列表的输出:

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

编辑:请记住,这取决于您的歌曲记录中恰好有一个“-”,从而界定了歌曲名称和艺术家。如果歌曲名称或歌手中的任何一个包含连字符,您将得到意外的行为。