python - 搜索字符串并删除包含字符串的行和下面的行
问题描述
我有一个文本文件,其中包含
### 174.10.150.10 on 2018-06-20 12:19:47.533613 ###
IP : 174.10.150.10 :
IP : ALL :
我目前有使用正则表达式搜索日期/时间字符串的代码。如何删除包含我找到的字符串的行?我想删除该行以及下面的行。
所以这两行都会被删除:
### 174.10.150.10 on 2018-06-20 12:19:47.533613 ###
IP : 174.10.150.10 :
我的代码目前只是在文本文件的底部添加了“无”。
import re
def run():
try:
with open('file.txt', 'r') as f:
with open('file.txt', 'a') as f2:
reg = re.compile('###\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.+(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{0,})\s###')
for line in f:
m = reg.match(line)
answer = raw_input("Delete line? ")
if answer == "y":
# delete line that contains "###" and line underneath
f2.write(str(m))
else:
print("You chose no.")
except OSError as e:
print (e)
run()
解决方案
通过一些基本的重构,结果如下...
import re
valid_lines = []
def run():
try:
with open('file.txt', 'r') as f:
reg = re.compile('###\s+\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}.+(\d{4}-\d{2}-\d{2}\s\d{2}:\d{2}:\d{2}.\d{0,})\s###\s?')
lines = f.readlines()
invalid_index = -10
for a in range(len(lines)):
reg_result = reg.match(lines[a])
if invalid_index == (a - 1):
# Skip the line underneath the invalid line
continue
if reg_result != None:
# If the line matches the regexp.
invalid_index = a
answer = raw_input("Delete line? ")
if answer.lower() != 'y':
print("You chose no.")
valid_lines.append(lines[a])
else:
valid_lines.append(lines[a])
with open('file.txt', 'w') as f:
# Override the file...
f.writelines(valid_lines)
except OSError as e:
print (e)
run()
如果您想删除以###
then 开头的任何行,也许您应该将其视为正则表达式:###.*
编辑:在您的正则表达式中,您应该\s?
在末尾添加 a 以可选地 match \n
,因为文件包含换行符。另外,使用fullmatch()
代替match()
.
推荐阅读
- java - 在游戏图块 Java 上覆盖游戏块
- python - 您可以在散景应用程序中嵌入 https 证书吗?Python
- javascript - 我应该在哪里绑定 React 组件中的方法?
- django - django context_processors,请求'function'对象没有属性'path'
- c# - c# 多部分表单数据编码
- excel - 这个excel VBA范围定义有什么错误?
- html - 在圆周上绝对定位元素
- javascript - 具有相同值的“顶部”属性显示不同
- reactjs - 错误:操作必须是普通对象。使用自定义中间件进行异步操作。但我没有异步功能
- javascript - 单击以打开 PDF - 您可能需要适当的加载程序来处理此文件类型