删除包含特定字符串的行

2024-05-13 02:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图从文本文件中读取文本,读取行,删除包含特定字符串的行(在本例中为“bad”和“naughty”)。 我写的代码是这样的:

infile = file('./oldfile.txt')

newopen = open('./newfile.txt', 'w')
for line in infile :

    if 'bad' in line:
        line = line.replace('.' , '')
    if 'naughty' in line:
        line = line.replace('.', '')
    else:
        newopen.write(line)

newopen.close()

我是这样写的,但没有成功。

有一点很重要,如果课文的内容是这样的:

good baby
bad boy
good boy
normal boy

我不希望输出有空行。 所以不喜欢:

good baby

good boy
normal boy

但就像这样:

good baby
good boy
normal boy

我应该从上面的代码中编辑什么?


Tags: 代码intxtiflineinfilereplacebaby
3条回答

您可以像这样使代码更简单、可读性更强

bad_words = ['bad', 'naughty']

with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

使用Context Managerany

您不能将该行包含到新文件中,而应该执行replace操作。

for line in infile :
     if 'bad' not in line and 'naughty' not in line:
            newopen.write(line)

我已使用此功能从文本文件中删除不需要的单词:

bad_words = ['abc', 'def', 'ghi', 'jkl']

with open('List of words.txt') as badfile, open('Clean list of words.txt', 'w') as cleanfile:
    for line in badfile:
        clean = True
        for word in bad_words:
            if word in line:
                clean = False
        if clean == True:
            cleanfile.write(line)

或者对目录中的所有文件执行相同的操作:

import os

bad_words = ['abc', 'def', 'ghi', 'jkl']

for root, dirs, files in os.walk(".", topdown = True):
    for file in files:
        if '.txt' in file:
            with open(file) as filename, open('clean '+file, 'w') as cleanfile:
                for line in filename:
                    clean = True
                    for word in bad_words:
                        if word in line:
                            clean = False
                    if clean == True:
                        cleanfile.write(line)

我相信一定有一个更优雅的方法来做,但这是我想要的。

相关问题 更多 >