hi there got a couple of probs, say in my text file i have:

abase
abased
abasement
abasements
abases

--------

This coding below is meant to find a word in a file and print all the lines to the end of the file. But it doesnt, it only prints out my search term and not the rest of the file.

search_term = r'\b%s\b' % search_term
    
    for line in open(f, 'r'):
        if re.match(search_term, line):
            if search_term in line:
                print line,

Say i searched for abasement, i would like the output to be:

abasement
abasements
abases


----------

My final problem is, i would like to search a file a print the lines my search term is in and a number of lines befer and after the searchterm. If i searched the text example above with 'abasement' and i defined the number of lines to print either side as 1 my output would be:

abased
abasement
abasements

numb = ' the number of lines to print either side of the search line '
    search_term = 'what i search'
    f=open("file")
    d={}
    for n,line in enumerate(f):
        d[n%numb]=line.rstrip()
        if search_term in line:
            for i in range(n+1,n+1+numb):
                print d[i%numb]
            for i in range(1,numb):
                print f.next().rstrip()

But i get a i get a Typeerror: unsupported operand type(s) for %: 'int' and 'str' which occurs at: d[n%numb] = line.rstrip()


Help please?

I don't use regex as a rule and it is not necessary in this case.

found = False
fp = open(fname, 'r')
for num, line in enumerate(fp):
    line = line.strip()
    if line.startswith(search_term):
        found = True
    if found:
        print num, line
fp.close()

and a number of lines before and after the search term

To do this, you will have to process the file twice, the first time to count the total number of records (so you can print the number of recs after the search term), and process a second time and print the info.

Say i searched for abasement, i would like the output to be:

abasement
abasements
abases

As woooee says, you don't have to use regex for this but if you do use it you can modify your first program as follows:

#!/usr/bin/env python
import re
f = "fsp.txt"
search_term = "abasement"
search_term = r'\b%s\b' % search_term

found = False
for line in open(f, 'r'):
    if not found:
        matchobj = re.match(search_term, line)
        if matchobj:
            found = True
    if found:
        print line,
This article has been dead for over six months. Start a new discussion instead.