【问题标题】:Reading a text file and showing only part of it some of it in python读取文本文件并在 python 中仅显示其中的一部分
【发布时间】:2020-10-15 10:57:45
【问题描述】:

所以我在 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

想知道是否有人可以提供帮助

【问题讨论】:

  • 看看字符串切片和split()函数。
  • 你的工作产生了什么代码?只是为了让我们可以看到你卡在哪里。

标签: python python-3.3


【解决方案1】:

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

【讨论】:

  • 您好,我尝试实现该代码,但它说“as”是无效语法
  • 您好,反正没必要,只是为了让代码更干净,我已经编辑了代码。但我认为它适用于 python 3.3。
  • @ViktorKelemen -- 你不需要在某个时候打电话给f.close()吗?
  • 这不是必需的,但确实如此,建议您可以在“text_of_songs = f.read()”行之后立即调用它,代码的工作方式相同。我已经编辑了我的代码。
  • 应该使用 with open('file') as f 约定而不是 f.read(),因为这可以确保文件句柄自动关闭,因为并非所有 Python 实现都会在 gc 时关闭文件句柄。
【解决方案2】:

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

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']

编辑:请记住,这取决于您的歌曲记录中恰好有一个“-”,用于分隔歌曲名称和艺术家。如果歌曲名称或艺术家包含连字符,您会得到意想不到的行为。

【讨论】:

  • 回溯(最近一次调用最后一次):第 78 行,在 + "-" + song_record.split("-")[1] TypeError: bad operand type for unary +: 'str '
  • @destoralater:哎呀,对不起。现在修好了。我忘记了最后一个代码块中的行溢出标记之一。现在应该可以工作了。或者只是把它们放在一行上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-04-30
  • 2014-10-17
相关资源
最近更新 更多