我有一个脚本,可以打印标题行之间的所有行,但它只适用于我的伪数据,所以我尝试在某个字符串之后匹配整行。你知道吗
假设我有一个文本文件中的数据:
Dumb Data
index1 0000
random data
index1 0000
random data
index2 0000
该脚本能够提取索引1之后的所有行,并在索引2之前停止,但它只能在索引行与if语句中的extactly匹配时工作。意思是如果我删除“index1”之后的所有内容,它就可以正常工作。因此,基于阅读这里的python文档https://docs.python.org/3.4/library/re.html,我尝试使用正则表达式。你知道吗
这是我的密码: 它与正则表达式部分一起工作,如果我将result1和result2替换为所需的提取字符串。我错过了什么?我用“.”来匹配“index1”后面的所有内容,对吗?你知道吗
import re
myvar = False
prog = re.compile('.')
result1 = prog.match('index1')
result2 = prog.match('index2')
with open('Sample Test.txt') as f:
for line in f:
if result1 in line:
myvar = True
print (line)
elif result2 in line:
myvar = False
print (line)
elif myvar == True:
print(line)
continue
当我试着运行它时得到了这个回溯:
Traceback (most recent call last): File "C:\mytest\test.py", line 10, in if result1 in line: TypeError: 'in ' requires string as left > operand, not _sre.SRE_Match
你没有正确使用regex。。。你应该这样做。你知道吗
相关问题 更多 >
编程相关推荐