我是Python的新手。我有2个词典:group1
和group2
,如果在词典中,我需要替换文本文件中的行为null / delete:
{'car': set(['ab', 'ef', 'ad', 'cd']), 'bike': set(['ac', 'de'])}
{'car': ['go', 'drive', 'enjoy'], 'bike': ['ride']}
我的档案:
!hello!!
mycar
car(ab,ef,ad,cd)
go
drive
enjoy
bike(ac,de)
ride
预期输出
!hello!!
mycar
必须将输出写入同一文件而不影响/其他行及其缩进!
答案 0 :(得分:0)
试试这个:
#!/usr/bin/env python
#-*- coding:utf-8 -*-
import re
path = 'your file path'
group1 = {'car': set(['ab', 'ef', 'ad', 'cd']), 'bike': set(['ac', 'de'])}
group2 = {'car': ['go', 'drive', 'enjoy'], 'bike': ['ride']}
f = open(path, 'r')
text = f.readlines()
f.close()
flag = 0
lines = []
for line in text:
for i in list(group1['car']):
if re.search(i, line):
flag = 1
break
if flag == 1:
flag = 0
continue
for i in list(group1['bike']):
if re.search(i, line):
flag = 1
break
if flag == 1:
flag = 0
continue
for i in group2['car']:
if re.search(i, line):
flag = 1
break
if flag == 1:
flag = 0
continue
for i in group2['bike']:
if re.search(i, line):
flag = 1
break
if flag == 1:
flag = 0
continue
lines.append(line)
f = open(path, 'w')
for l in lines:
f.write(l)
f.close()