[英]How do you split a string into lines with a regular expression in Python?
我有一个包含4行的日志文件,例如:
12/12/2015 18:00:00 Computer:PC_1 (Rel:7.8.x)
ERROR message: 1245456487
The wifi was not available
The user needs to validate
现在,我想使用Python中的正则表达式将第一行的第二行拆分为:
line1 == '12/12/2015 18:00:00 Computer:PC_1 (Rel:7.8.x)'
line2 == '2 ERROR message: 1245456487'
您可以简单地将日志文件拆分成如下所示的行列表:
with open('mylogfile.txt') as f:
lines = list(f)
lines[0]
将是第一行, lines[1]
是第二行,依此类推。
可以将str
的实例拆分为几行,如下所示:
>>> s="""12/12/2015 18:00:00 Computer:PC_1 (Rel:7.8.x)
... ERROR message: 1245456487
... The wifi was not available
... The user needs to validate"""
>>> lines = s.splitlines()
>>> lines[0]
'12/12/2015 18:00:00 Computer:PC_1 (Rel:7.8.x)'
>>> lines[1]
'ERROR message: 1245456487'
无论哪种情况,您都不需要此任务的正则表达式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.