开发者

Searching for text in a file

开发者 https://www.devze.com 2022-12-14 04:54 出处:网络
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 pri开发者_JAVA技巧nt all the lines to the

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 pri开发者_JAVA技巧nt 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()


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.


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
0

精彩评论

暂无评论...
验证码 换一张
取 消