Python search text file, print characters following a string

13,169

I'd do it like:

WANTED = 20 #or however many characters you want after 'Figure'

with open('mytext.txt') as searchfile:
    for line in searchfile:
        left,sep,right = line.partition('Figure')
        if sep: # True iff 'Figure' in line
            print(right[:WANTED])

see: str.partition

Share:
13,169
PeterFoster
Author by

PeterFoster

Updated on June 24, 2022

Comments

  • PeterFoster
    PeterFoster almost 2 years

    I want to be able to search a document for a given string and find the context for each instance. For example, search a document for "Figure" and return X characters following that string (returns "-1 Super awesome figure" from "Figure-1 Super awesome figure. next sentence.")

    I know how to print either: A) each instance of that string

    mystring = "Figure"
    with open('./mytext.txt', 'r') as searchfile:
        for line in searchfile:
            if mystring in line:
                print(mystring)
    

    but that's no help; or B) each line containing that string

    for line in open('./mytext.txt', "r"):
        if "Figure" in line:
            print(line) 
    

    which returns all of the text in the entire line, before and after, which is cumbersome for my purposes.

    Can I split a line at "mystring" and return X characters following the split? Or is there altogether a better approach?

  • PeterFoster
    PeterFoster over 10 years
    This is exactly what I was looking for, and it works great. I'm sure other methods will return similar results, but this I understand. Thanks,