我有一个这样的文件(聊天文件,大约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)
答案 0 :(得分:1)
如果我正确理解了这个问题,您可以使用以下内容:
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)
答案 1 :(得分:1)
我做到了!
代码:
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)
关闭:))
答案 2 :(得分:1)
你有一个很大的文件,我不建议使用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)
答案 3 :(得分:0)
匹配当前行后,您需要打印所有值,直到另一个用户行。所以你需要为任何用户添加一个正则表达式,以便知道何时停止打印行并再次检查一些用户。