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

2024-04-20 01:08:30 发布

您现在位置: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

只是想知道是否有人能帮忙


Tags: the代码字母歌曲happycreator艺术家文本文件
2条回答

如果您的歌曲存储在“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']

编辑:请记住,这取决于您的歌曲记录中正好有一个“-”,它界定了歌曲名称和艺术家。如果歌曲名称或艺术家包含连字符,则会出现意外行为

相关问题 更多 >