Python string split()方法在读取IRC时导致索引错误

问题描述 投票:-1回答:1

我正在创建一个抽搐聊天机器人来阅读我的流上的聊天。但是当我尝试将.split()传入的字符串分成单独的字符串以隔离用户名和消息时,它会显示一个额外的'和[“'”]。当我尝试通过索引单独打印字符串时,我得到一个索引错误。

以下是连接聊天聊天的代码,以及当我在聊天中输入“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![email protected] PRIVMSG #username:test

但是,当我拆分字符串并打印字符串(部分)列表时,它会生成:[“b'”,“username!username @ username.tmi.twitch.tv PRIVMSG #username','test']'[”' “]

python string irc twitch
1个回答
0
投票

你正在读字节。因此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'
© www.soinside.com 2019 - 2024. All rights reserved.