简体   繁体   English

删除包含某个单词的所有行

[英]Remove all lines containing a certain word

Having a string like this one:有这样一个字符串:

AAAA AAAA
BBBB BBBB
CCCC CCCC
DDXD DDDD
EEEE EEEE
FXFF RRRR

How could I remove all the lines containing an "X"?如何删除所有包含“X”的行?

I know that I could do it from a txt file, but I would like to do it directly from the string...我知道我可以从 txt 文件中执行此操作,但我想直接从字符串中执行此操作...

The result must be:结果必须是:

AAAA AAAA
BBBB BBBB
CCCC CCCC
EEEE EEEE

I tried with:我试过:

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)

Try this:尝试这个:

with open("file.txt", "r") as f:
    lines = f.readlines()
with open("file.txt", "w") as f:
    for line in lines:
        if not "X" in line:
            f.write(line)

You can easily accomplish this by using list comprehension.您可以使用列表推导轻松完成此操作。 Iterate through your string (split by \n ) and if a row is spotted without an X , then append it to a list.遍历您的字符串(由\n分割),如果发现一行没有X ,则 append 将其添加到列表中。

stringRemoval = "AAAA AAAA\nBBBB BBBB\nCCCC CCCC\nDDXD DDDD\nEEEE EEEE\nFXFF RRRR"
cleanString = [line for line in stringRemoval.split('\n') if 'X' not in line]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM