这是我的代码我的目标是从大文本文件中打印一个特定的整行,其中字符串等于" SAMPLE TYPE"当我尝试在对象中打印如何从整个文件打印指定的行
import re
target = open("debug.txt", "r")
for line in target:
search=re.search("[SAMPLE TYPE]",line)
v1=search
print v1
输出:
None
None
None
None
None
<_sre.SRE_Match object at 0x7f870b7d5578>in this place instead of this i need to print the specifed line and i dont want the lines which doesnt contain specifed string.
我的输入文件数据:
HLS| 04/14/16 17:56:58:933 |hls_tsr_module.cpp|ReceiveData |418 |DEBUG: Data copied to TSD from TSR is 0
HLS| 04/14/16 17:56:58:933 |mpm_h264.cpp |FrameType |1341|DEBUG: AU_DELIM NALU Unit Type
HLS| 04/14/16 17:56:58:933 |mpm_h264.cpp |FrameType |1341|DEBUG: SEI NALU Unit Type
HLS| 04/14/16 17:56:58:933 |mpm_h264.cpp |FrameType |1341|DEBUG: NON_IDR_PICTURE NALU Unit Type
HLS| 04/14/16 17:56:58:933 |mpm_h264.cpp |FrameType |1377|DEBUG: B Frame Received
HLS| 04/14/16 17:56:58:933 |hls_tsd_module.cpp|ProcessVideoBuffer |4151|DEBUG: SAMPLE TYPE: B - FRAME PTS: 8573002542 DTS: 8573002542
HLS| 04/14/16 17:56:58:933 |hls_tsd_module.cpp|ProcessVideoBuffer |4193|DEBUG: Video send pts 8573002542
HLS| 04/14/16 17:56:58:933 |hls_tsm_module.cpp|AlternateFrameInterLeave |11770|DEBUG: Audio Record Status is 1
HLS| 04/14/16 17:56:58:934 |hls_tsd_module.cpp|ProcessVideoBuffer |4261|DEBUG: Frame video pts 8573004043
HLS| 04/14/16 17:56:58:934 |hls_tsm_module.cpp|AlternateFrameInterLeave |11770|DEBUG: Audio Record Status is 1
HLS| 04/14/16 17:56:58:934 |hls_tsd_module.cpp|SegmentStream |1597|DEBUG: Not an AV/Subtitle Packet 256
HLS| 04/14/16 17:56:58:934 |mpm_h264.cpp |FrameType |1341|DEBUG: AU_DELIM NALU Unit Type
HLS| 04/14/16 17:56:58:934 |mpm_h264.cpp |FrameType |1341|DEBUG: SEI NALU Unit Type
HLS| 04/14/16 17:56:58:934 |mpm_h264.cpp |FrameType |1341|DEBUG: NON_IDR_PICTURE NALU Unit Type
HLS| 04/14/16 17:56:58:934 |mpm_h264.cpp |FrameType |1377|DEBUG: B Frame Received
HLS| 04/14/16 17:56:58:934 |hls_tsd_module.cpp|ProcessVideoBuffer |4151|DEBUG: SAMPLE TYPE: B - FRAME PTS: 8573004043 DTS: 8573004043
答案 0 :(得分:1)
import os
os.system('grep -rnw "[FOLDER_NAME]" -e "SEARCH_STRING" > OP.txt')
答案 1 :(得分:1)
Python regex search
方法返回匹配对象或None(如果没有找到)。要从匹配对象中获取字符串,您需要调用.group()
。
In [1]: import re
In [2]: re.search("a", "aaa")
Out[2]: <_sre.SRE_Match at 0x7fe3514e98b8>
In [3]: re.search("a", "aaa").group()
Out[3]: 'a'
答案 2 :(得分:1)
这是如何做到的:
with open("debug.txt", "r") as target:
for line in target:
if "[SAMPLE TYPE]" in line:
print(line)
请注意,我使用上下文管理器(with
语句)来打开文件。此外,如果您只是想在另一个字符串中找到子字符串,则不需要re
。
答案 3 :(得分:0)
尝试:
if search:
print(line)
正在返回的正则表达式对象在无法找到任何内容时将计算为False。
答案 4 :(得分:0)
从documentation:re.search返回MatchObject个实例。该文档向您展示了如何访问搜索到的字符串,例如v1.group(0)
。