file1.txt 有以下几行:
[SUM] 0.00-34.53 sec 2.11 GBytes 524 Mbits/sec sender
[SUM] 0.00-34.53 sec 2.11 GBytes 524 Mbits/sec sender
[SUM] 0.00-34.62 sec 2.36 GBytes 586 Mbits/sec sender
[SUM] 0.00-34.62 sec 2.36 GBytes 586 Mbits/sec sender
[SUM] 0.00-34.75 sec 2.39 GBytes 591 Mbits/sec receiver
[SUM] 0.00-34.75 sec 2.39 GBytes 591 Mbits/sec receiver
[0] 0.00-34.53 sec 0.00 Bytes 0.00 bits/sec receiver
[0] 0.00-34.75 sec 0.00 Bytes 0.00 bits/sec sender
将以 [SUM] 开头并以 sender 和 receiver 结尾的行打印到另一个文本文件-file2.txt 中。
以下是代码:
with open(r"C:\Users\file1.txt", 'r') as f:
contents = f.read()
s=contents
def my_function1():
regex = "^\s*\[SUM\]\s*[0-9\-\.]+\s+sec(?!\s+0\.00 Bytes).*sender.*"
items=re.findall(regex,s,re.MULTILINE)
for y in items:
file=open('file2.txt', "a")
file.write(str(y))
file.write("\n")
file.close()
def my_function2():
regex = "^\s*\[SUM\]\s*[0-9\-\.]+\s+sec(?!\s+0\.00 Bytes).*receiver.*"
items=re.findall(regex,s,re.MULTILINE)
for y in items:
file=open('file2.txt', "a")
file.write(str(y))
file.write("\n")
file.close()
#print(y)
my_function1()
my_function2()
它将 file2.txt 中的输出写为:
[SUM] 0.00-34.53 sec 2.11 GBytes 524 Mbits/sec sender
[SUM] 0.00-34.53 sec 2.11 GBytes 524 Mbits/sec sender
[SUM] 0.00-34.62 sec 2.36 GBytes 586 Mbits/sec sender
[SUM] 0.00-34.62 sec 2.36 GBytes 586 Mbits/sec sender
[SUM] 0.00-34.62 sec 2.36 GBytes 586 Mbits/sec sender
[SUM] 0.00-34.75 sec 2.39 GBytes 591 Mbits/sec receiver
[SUM] 0.00-34.75 sec 2.39 GBytes 591 Mbits/sec receiver
预期:仅打印一次
[SUM] 0.00-34.53 sec 2.11 GBytes 524 Mbits/sec sender
[SUM] 0.00-34.62 sec 2.36 GBytes 586 Mbits/sec sender
[SUM] 0.00-34.75 sec 2.39 GBytes 591 Mbits/sec receiver