python怎么删除包含指定中文的行
发布网友
发布时间:2022-04-22 04:33
我来回答
共3个回答
热心网友
时间:2022-07-12 02:14
#!/usr/bin/env python
#coding=utf-8
def read_del_list(path):
del_list = list()
with open(path, 'w') as file_handle:
for row in file_handle:
del_list.append(row.strip())
return del_list
def filte_file(from_file, to_file, del_list):
with open(from_file) as file_handle_from:
with open(to_file) as file_handle_to:
for row in file_handle_from:
if not any(key_word in row for key_word in del_list):
file_handle_to.write(row)
if __name__ == '__main__':
del_list = read_del_list(r"del_list.txt") #读取过滤规则
filte_file(r"source.txt", "output.txt", del_list)#过滤文件
追问呃,del_list.txt里面的内容被删除了,但是output.txt里面生成的文件却没有去除掉需要删除的内容。。。。
具体文件以及要求已经传到百度网盘(http://pan.baidu.com/s/1i3yx4Qp)了,这么说起来太纠结了。。。囧。。。
追答
对不起,忘记加打开模式
#!/usr/bin/env python
#coding=utf-8
def read_del_list(path):
del_list = list()
with open(path, 'r') as file_handle:
for row in file_handle:
del_list.append(row.strip())
return del_list
def filte_file(from_file, to_file, del_list):
with open(from_file, 'r') as file_handle_from:
with open(to_file, 'w') as file_handle_to:
for row in file_handle_from:
if not any(key_word in row for key_word in del_list):
file_handle_to.write(row)
if __name__ == '__main__':
del_list = read_del_list(r"del.txt") #读取过滤规则
filte_file(r"input.txt", "output.txt", del_list)#过滤文件
热心网友
时间:2022-07-12 02:14
fa=open('del.txt','rt')
fb=open('output.txt','rt')
fc=open('c.txt','wt')
a=set()
for line in fa:
a.add(line.strip())
fa.close()
for line in fb:
exist=False
for m in a:
if line.startswith(m):
exist=True
break
if exist: print('skip '+line)
else: fc.write(line)
fb.close()
fc.close()
这段代码是借用其他网友的,看了下没有错误,省的自己敲了,你看哪里不明白。或者你把自己的代码粘上来帮你检查也行。追问运行了一下,跟上面那位同学的代码一样,最后的输出的output.txt内容为空。具体文件以及要求已经传到百度网盘(http://pan.baidu.com/s/1i3yx4Qp)了,这么说起来太纠结了。。。囧。。。
热心网友
时间:2022-07-12 02:15
两个for循环跑吧。。。追问talk is cheap show me the code