Python - 从同一变量向文本文件添加多个值

Python - Add multiple values to text file from same variable

我正在使用 Python 开发一个 Twitch IRC 机器人,最近我实现了歌曲请求。奇怪的是,我遇到的主要问题是将歌曲存储在单独的文本文件、列表或集合中。目前,这是我检索列表中歌曲的方式:

  1. 用户在 !songrequest 中输入 [URL]。
  2. Bot 处理 URL 并从中提取歌曲名称。
  3. Bot 发送确认消息,并将歌曲名称存储在变量中。

因此,由于歌曲标题都存储在同一个变量中,它会不断地覆盖自己,即使放在一个集合中也是如此。我是 Python 的新手,所以如果有人能帮助我并告诉我如何将每首独特的歌曲标题发送到集合、列表等,我将非常高兴!提前致谢!

我的代码:

if message.startswith("!songrequest"):
        request = message.split(' ')[1]
        youtube = etree.HTML(urllib.urlopen(request).read())
        video_title = youtube.xpath("//span[@id='eow-title']/@title")
        song = ''.join(video_title)
        requests = set()
        requests.add(song + "\r\n")
        sendMessage(s, song + " has been added to the queue.")
        with open("requests.txt", "w") as text_file:
            text_file.write(str(requests))
        break

如果您发现任何其他清理我的编码的建议,请在下面告诉我!

让我们通过创建一个函数来清理它:

if message.startswith("!songrequest"):
    song = message.split(' ', 1)[1]   # Add max=1 to split()
    message = request_song(song)
    sendMessage(s, message)
    break

现在我们来编写request_song(title)函数。我认为你应该保留一个唯一的请求歌曲列表,并告诉用户是否已经请求了一首歌曲。当你播放一首歌时,你可以清除请求(大概当你播放它时,每个请求它的人都会听到它并感到满意)。该函数可以 return 一条适当的消息,具体取决于它采取的操作。

def request_song(song:str) -> str:
    """
    Add a song to the request queue. Return a message to be sent
    in response to the request. If the song is new to the list, reply
    that the song has been added. If the song is already on the list,
    or banned, reply to that effect.
    """
    if song.startswith('http'):
        if 'youtube' not in song:
            return "Sorry, only youtube URLs are supported!"

        youtube = etree.HTML(urllib.urlopen(request).read())
        song_title = youtube.xpath("//span[@id='eow-title']/@title")
    else:
        song_title = song.strip().lower()

    with open('requests.txt') as requestfile:
        requests = set(line.strip().lower() for line in requestfile)

    if song_title in requests:
        return "That song is already in the queue. Be patient!"

    # Just append the song to the end of the file
    with open('requests.txt', 'a') as f:
        print(file=f, song_title)

    return "'{}' has been added to the queue!".format(song_title)