views:

152

answers:

2

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:
            f = 1
        if f: 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()
+1  A: 

For the first part of the question, unindent your if f: print line,. Otherwise, you're only trying to print when the regex matches.

It's not clear to me what your question is in the second part. I see what you're trying to do, and your code, but you've not indicated how it misbehaves.

Blair Conrad
i get a Typeerror: unsupported operand type(s) for %: 'int' and 'str'which occurs at: d[n%numb] = line.rstrip()
harpalss
you get a type error because numb is a string. try setting numb to an actual number and put the description as a comment
Mark Peters
+1  A: 

For the first part the algorithm goes like this (in pseudo code):

found = False
for every line in the file:
    if line contains search term:
        found = True
    if found:
        print line
Bryan Oakley
If he wants to print every line after the match, wouldn't it be better to stop checking once a match is found and then print every line after it?
danben
@danben: yes. That first 'if' could be rewritten as "if not found and line contains the search term"
Bryan Oakley