【问题标题】:Python string split() method causes index error when reading IRCPython字符串split()方法读取IRC时导致索引错误
【发布时间】:2019-03-26 03:28:15
【问题描述】:

我正在创建一个 twitch 聊天机器人来阅读我的信息流中的聊天内容。但是当我尝试将传入的字符串 .split() 分成单独的字符串以隔离用户名和消息时,它会显示一个额外的'和 ["'"]。当我尝试按索引单独打印字符串时,出现索引错误。

以下是连接twitch聊天的代码,以及当我在聊天中输入“test”时的结果。

from settings import *
import socket
import threading

class twitch:
    def __init__(self, host, port, nick, pwd, channel):
        self.s = socket.socket()
        self.s.connect((host, port))
        self.s.send(bytes("PASS " + pwd + "\r\n", "UTF-8"))
        self.s.send(bytes("NICK " + nick + "\r\n", "UTF-8"))
        self.s.send(bytes("JOIN #" + channel + " \r\n", "UTF-8"))
        self.s.send(bytes("PRIVMSG #" + channel + " :" + "Connected " + "\r\n", "UTF-8"))
        self.alive = True

        readerthread = threading.Thread(target=self.read_chat)
        readerthread.start()

    def read_chat(self):
        while self.alive:
            for line in str(self.s.recv(1024)).split('\\r\\n'):
                if "PING :tmi.twitch.tv" in line:
                    print(time.strftime("%H:%M:%S"), "PONG :tmi.twitch.tv")
                    s.send(bytes("PONG :tmi.twitch.tv\r\n", "UTF-8"))
                else:
                    print(line)
                    parts = line.split(":")
                    print(parts)

def main():
    tc = twitch(HOST, PORT, NICK, PASS, CHANNEL)

将字符串(行)打印到控制台会生成:b':username!username@username.tmi.twitch.tv PRIVMSG #username :test

但是,当我拆分字符串并打印字符串(部分)列表时,它会产生以下结果: [“b”,'用户名!用户名@用户名.tmi.twitch.tv PRIVMSG #username','测试'] ' ["'"]

【问题讨论】:

    标签: python string irc twitch


    【解决方案1】:

    您正在读取字节。因此,b'...'。
    What does the 'b' character do in front of a string literal?


    将其转换为字符串,然后进行处理。
    Convert bytes to a string?


    链接中的代码。

    >>> b"abcde"
    b'abcde'
    
    # utf-8 is used here because it is a very common encoding, but you
    # need to use the encoding your data is actually in.
    >>> b"abcde".decode("utf-8") 
    'abcde'
    

    【讨论】:

    • 非常感谢您的回复。我尝试添加 x = line.decode("UTF-8") 并得到: AttributeError: 'str' object has no attribute 'decode'
    • for line in str(self.s.recv(1024)).split('\\r\\n'): 您似乎正在转换为字符串。移除石膏。 for line in (self.s.recv(1024)).split('\\r\\n'): 然后解码字节
    猜你喜欢
    • 2016-05-14
    • 1970-01-01
    • 2018-04-06
    • 2016-05-18
    • 1970-01-01
    • 1970-01-01
    • 2017-06-04
    • 1970-01-01
    • 2016-02-08
    相关资源
    最近更新 更多