您的位置:首页 > 编程语言 > Python开发

python实现连续去掉n行相同字符

2018-03-24 16:01 399 查看
例子中实现了去掉3行相同字符,大家可以将3行改成n行,只需要进行判断,在最后一行进行换行操作即可。


# -*- coding: utf-8 -*-
'''
去除某文本中连续3行相同的字符,并将其替换成一行空白行
'''
import re
def fenhang(infile,outfile):

infopen = open(infile,'r',encoding='utf-8')
outopen = open(outfile,'w',encoding='utf-8')
lines = infopen.readlines()
db = []
db1 = []
for line in lines:
db.append(line)
for i in range(0,len(db)):
sett = db[i].strip()
db1.append(sett)
for y in range(0,len(db1)):
if y <= len(db1)-2 and db1[y]=='O' and db1[y+1]=='O' and db1[y+2]=='O':#遇到第一行进行判断
outopen.write(db1[y]+'pjh')#注意不加换行符
elif y <= len(db1) - 2 and db1[y] == 'O' and db1[y + 1] == 'O':#遇到第二行进行判断
str(db1[y]).replace('O','')#将其替换成单个字符,注意,不加换行符
outopen.write(db1[y])
elif y <= len(db1) - 2 and db1[y] == 'O':#遇到第三行进行判断
str(db1[y]).replace('O', '')
outopen.write(db1[y]+'\n')#注意:添加换行符
else:
outopen.write(db1[y]+'\n')

infopen.close()
outopen.close()
fenhang("源文件路径","目标文件路径")
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: