Delete lines containing a specific word

Martin Marcher martin at marcher.name
Sun Jan 6 13:49:34 EST 2008


On Sunday 06 January 2008 18:21 Francesco Pietra wrote:

> Please, how to adapt the following script (to delete blank lines) to
> delete lines containing a specific word, or words?
> 
> f=open("output.pdb", "r")
> for line in f:
> line=line.rstrip()
> if line:
> print line
> f.close()

>>> import re
>>> s = ["hello", "world", "", "\t ", " ", "#asdfasdf"]
>>> pattern = re.compile("^\s*$")
>>> #only "hello" should be printed as "world" is a word we want to skip
>>> for line in s:
...     if "world" in line:
...             continue
...     if pattern.match(line):
...             continue
...     if line.startswith("#"):
...             continue
...     print line
...
hello
>>>

you have to adapt it to be able to match more than a single word

> If python in Linux accepts lines beginning with # as comment lines, please
> also a script to comment lines containing a specific word, or words, and
> back, to remove #.

yes lines starting with a "#" are comments in python but that shouldn't be
of concern for your input data. I don't quite get what you want here...

hth
martin

-- 
http://noneisyours.marcher.name
http://feeds.feedburner.com/NoneIsYours




More information about the Python-list mailing list