Python: Find closest match of multiple words in text file
Question: I need to parse multiple financial statement .txt files similarly to this
[one](http://www.sec.gov/Archives/edgar/data/320193/000104746904035975/0001047469-04-035975.txt).
The .txt files do not have standardized format. However, they have similar
headings. My objective is to extract the section of the .txt files that starts
with the following keywords `['Item', '7', 'Management', 'Analysis']` and ends
with `['Item', '8', 'Financial', 'Statements']`. The order of the words in
both list matter and `['Item', '7', 'Management', 'Analysis']` comes before
`['Item', '8', 'Financial', 'Statements']`.

What I have in mind is to start with:

    
    
    fdir = open('C:\\0001193125-13-416534.txt','r')
    lines = fdir.readlines()
    

and loop over each line in `lines` and use
[`difflib.get_close_matches`](http://stackoverflow.com/questions/10018679/python-
find-closest-string-from-a-list-to-another-string) to find the above keywords.
However, I have two issues: (1) How can I use `difflib` to search for more
than one word? (2) I know that `difflib` will simply extract the match word,
but how can I use it to find the `index` (location in the list `lines`) of
where exactly in `lines` are located these words?

Let me add a third issue: Is using `.readlines()` the appropriate way to read
the txt file and start searching for the match words or should I simply use
`.read()`?


Answer: You can use `re` here with f.read().

f.read() return a string whereas f.readlines() returns a list.

    
    
    import re
    x=f.read()
    print re.findall(r"Item(?:(?!Item).)*7(?:(?!Item|7).)*Management(?:(?!Item|7|Management).)*Analysis[\s\S]*Item(?:(?!Item).)*8(?:(?!Item|8).)*Financial(?:(?!Item|8|Financial).)*Statements",x)
    

