【发布时间】:2016-01-25 01:12:37
【问题描述】:
我正在尝试解析文件并在字符串列表中搜索关键字。我需要在每次出现之前和之后返回“n”个字符。我让它在没有正则表达式的情况下工作,但它不是很有效。知道如何对正则表达式和 findall 做同样的事情吗? Lookup 是一个字符串列表。这就是我没有正则表达式的情况:
with open(file, 'r') as temp:
for num, line in enumerate(temp, 1):
for string in lookup:
if string in line:
# Split the line in 2 substrings
tmp1 = line.split(string)[0]
tmp2 = line.split(string)[1]
# Truncate only 'n' characters before and after the keyword
tmp = tmp1[-n:] + string + tmp2[:n]
# Do something here...
这是正则表达式的开始:
with open(file, 'r') as temp:
for num, line in enumerate(temp, 1):
for string in lookup:
# Regex search with Ignorecase
searchObj = re.findall(string, line, re.M | re.I)
if searchObj:
print "search --> : ", searchObj
# Loop trough searchObj and get n characters
【问题讨论】:
标签: python regex string file findall