繁体   English   中英

蟒蛇。 如何从文件中获取所需的行

[英]Python. How to get needed lines from file

我有一个这样的文件(聊天文件,约5GB)

XX, XX[14:59]: 
hello YY.
how are you today? 
YY, YY [14:59]: 
Hi
good, thank you, and you~
XX, XX[15:00]: 
thanks, I am good) 
YY, YY [15:00]: 
;)

我写了一些正则表达式,以便可以看到名称更改。

def is_service_desk_line(line):
    return re.match("XX, XX \[[0-9]+:[0-9]+[ A-Z]*\]:", line)


def is_someone_else_line(line):
    return re.match("YY, YY *\[[0-9]+:[0-9]+[ A-Z]*\]:", line)

我不知道如何读取文件以及如何设置“触发器”(例如,一旦该行与服务台行匹配,就开始写属于用户XX的下一行,直到该行与某人的其他行匹配为止。

我只需要属于XX用户的消息行。

我知道如何在Python中读取文件,但是如何设置“触发器”?

更新:

我需要的输出只是属于XX用户的一行:

hello YY.
how are you toda?
thanks, I am good)

如果我对问题的理解正确,则可以使用以下方法:

f = open("input_file")
lines = f.readlines()
f.close()

for line in lines:
    if is_service_desk_line(line):
        print("This is a service desk line", line)
    elif is_someone_else_line(line):
        print("This is someone else", line)
    else:
        print("This is neither", line)

如果您只希望来自用户XX的行,则只需使用if语句(否,否则,等等),它将仅输出该用户的行。

编辑

要仅输出用户XX的行,可以使用以下命令:

f = open("input.txt")
lines = f.readlines()
f.close()

print_line = False

for line in lines:
    if is_someone_else_line(line):
        print_line = False

    if print_line:
        print(line)

    if is_service_desk_line(line):
        print_line = True

输出为:

hello YY.

how are you today? 

thanks, I am good) 

我做的!

编码:

def get_messages(w_file, r_file):
    trigger = ""
    someone_else_line = ""
    with open(w_file, "wb") as w:
        with open(r_file, "r") as r:
            for line in r:
                if is_service_desk_line(line):
                    trigger = line
                    continue
                elif is_someone_else_line(line) or is_different_support(line):
                    trigger = line
                    someone_else_line = trigger
                    continue
                elif line.startswith("From"):
                    trigger = someone_else_line

                elif is_service_desk_line(trigger):
                    w.write(line)

封闭:)

您的文件很大,我不建议您使用readlines()将整个内容读入内存

内存有效的版本将遵循以下原则:

out_flag = False

with open('input_file.txt', 'r') as in_file:
    for line in in_file:
        if is_service_desk_line(line):
            out_flag = True  # sets output flag
            continue  # skips that line
        if is_someone_else_line(line):
            out_flag = False  # sets output flag
        if out_flag:
            print(line)

匹配当前行之后,需要打印所有值,直到另一个用户行为止。 因此,您需要为任何用户添加一个正则表达式,以知道何时停止打印行并再次检查某个用户。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM