开发者

Python - Stripping timestamps and username from line in file

I'm writing a script that will print a random line of text from a file into an XCHAT channel. So far it works fine, but I want to add one last bit of functionality.

I have logs with, for example, "Oct 23 12:07:59 (nickname> " appearing before every line of text. I just want to print the parts of the lines that follow the "(nickname>", how can I do this?

__module_name__ = "ran.py"
__module_version__ = "1.0"
__module_description__ = "script to add random text to channel messages"

import xchat
import random

def ran(message):
    message = random.choice(open("E:/logs/myfile.log", "r").readlines())
    return(message)


def ran_cb(word, word_eol, userdata):
    message 开发者_运维技巧= ''
    message = ran(message)
    xchat.command("msg %s %s"%(xchat.get_info('channel'), message))
    return xchat.EAT_ALL


xchat.hook_command("ran", ran_cb, help="/ran to use")


If the first > character is exactly the place to split, then try:

toBeIgnored, toBeUsed = line.split('>', 1)


I think > can be used as separator, so:

_, message = message.split('>', 1)

will split line into 2 part, first part (underscore while it is not important) with "Oct 23 12:07:59 (nickname" and second with text after >

You can use it in ran():

def ran(message):
    message = random.choice(open("E:/logs/myfile.log", "r").readlines())
    _, message = message.split('>', 1)
    return(message)


I would have asked in the comments but I don't have enough rep. Does/Can your user's nicknames contain ">" character? If not, you can use the split command:

message = random.choice(open("E:/logs/myfile.log", "r").readlines())
text = message.split("> ", 1)[1]
return(text)

Or you can use a single line:

message = random.choice(open("E:/logs/myfile.log", "r").readlines()).split("> ", 1)[1]
return(message)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜