Regex: get accented letters with spaces
Question: I'm trying to extract a keyword from a JSON string and get the context of the
word. My string looks like:

**JSON**

    
    
    {"1" : "Na casa de meu Pai há muitos aposentos; se não fosse assim, eu lhes teria dito. Vou preparar-lhes lugar."}
    

Currently, my Python code is:

**Python**

    
    
    re.findall(regex, string)
    

I want to provide a word (e.g. _Pai_) and get the words before and after the
keyword. My script will count all the occurrences of the keyword and make a
list of contextual words.

My problem is: how do I get the accented letters with whitespaces, commas,
dots, etc? What is the best approach: list the desired chars or exclude the
unwanted? Something like:

    
    
    ([^\"]+)Pai([^\"$]+)
    


Answer: Load your JSON data via `json.load()` or `json.loads()`, then use the
[`nltk.ConcordanceIndex`](http://stackoverflow.com/a/8898784/771848) that
would help you to explore the words around a specific word in a text, example:

    
    
    import nltk
    
    text = 'Na casa de meu Pai há muitos aposentos; se não fosse assim, eu lhes teria dito. Vou preparar-lhes lugar.'
    tokens = nltk.word_tokenize(text)
    
    c = nltk.ConcordanceIndex(tokens, key=lambda s: s.lower())
    result = []
    for offset in c.offsets('Pai'):
        result += tokens[offset - 2: offset]
        result += tokens[offset + 1: offset + 3]
    
    print(result)
    

Prints `['de', 'meu', 'há', 'muitos']`.

