【问题标题】:Python - Add multiple values to text file from same variablePython - 从同一变量向文本文件添加多个值
【发布时间】:2016-06-01 15:47:29
【问题描述】:

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

  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

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

【问题讨论】:

  • 您希望对文本文件做什么?
  • @tzaman 我还没有考虑过,主要是让我能够通读并播放列出的歌曲,但是我可能会尝试找到一种方法来拉弦在文件中并自动播放它们。
  • 那么为什么要一个文件而不是仅仅保存一个内存字典/set/etc?
  • @tzaman 也可以,文本文件只是一个例子。
  • 您只需要在某个更持久的地方声明您的集合,而不是每次都创建一个新集合。例如,如果您有一个机器人类,您可以在 __init__ 方法中输入 self.requests = set(),然后在代码中输入 self.requests.add

标签: python python-2.7 bots irc twitch


【解决方案1】:

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

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) 函数。我认为您应该保留一个唯一的请求歌曲列表,并告诉用户是否已经请求了歌曲。当你播放一首歌时,你可以清除请求(大概当你播放它时,请求它的每个人都会听到它并感到满意)。该函数可以返回适当的消息,由它采取的操作决定。

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)

【讨论】:

  • 谢谢,但是当我运行程序时,它在def request_song(song:str) -> str: 行上给我一个无效的语法错误,指向冒号。我尝试了我所知道的一切(这并不多:P)来修复它,但我无法解决错误。有什么想法吗?
  • 如果您使用的是旧版本的 python,请摆脱它:request_song(song):
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多