Python - regex relation extraction
Question: As a part of schoolwork we have been given this code:

    
    
    >>> IN = re.compile(r'.*\bin\b(?!\b.+ing)')
    >>> for doc in nltk.corpus.ieer.parsed_docs('NYT_19980315'):
    ...     for rel in nltk.sem.extract_rels('ORG', 'LOC', doc,
    ...                corpus='ieer', pattern = IN):
    ...         print(nltk.sem.rtuple(rel))
    

We are asked to try it out with some sentences of our own to see the output,
so for this i decided to define a function:

    
    
    def extract(sentence):
        import re
        import nltk
    
        IN = re.compile(r'.*\bin\b(?!\b.+ing)')
        for rel in nltk.sem.extract_rels('ORG', 'LOC', sentence, corpus='ieer', pattern = IN):
            print(nltk.sem.rtuple(rel))
    

When I try and run this code:

    
    
    >>> from extract import extract
    >>> extract("The Whitehouse in Washington")
    

I get the gollowing error:

    
    
    Traceback (most recent call last):
      File "<pyshell#1>", line 1, in <module>
        extract("The Whitehouse in Washington")
      File "C:/Python34/My Scripts\extract.py", line 6, in extract
        for rel in nltk.sem.extract_rels('ORG', 'LOC', sentence, corpus='ieer', pattern = IN):
      File "C:\Python34\lib\site-packages\nltk\sem\relextract.py", line 216, in extract_rels
        pairs = tree2semi_rel(doc.text) + tree2semi_rel(doc.headline)
    AttributeError: 'str' object has no attribute 'text'
    

Can anyone help me understand where I am going wrong in my function? The
correct output for the test sentence should be:

    
    
    [ORG: 'Whitehouse'] 'in' [LOC: 'Washington']
    


Answer: If you see the method definition of
[extract_rels](http://www.nltk.org/_modules/nltk/sem/relextract.html), it
expects the parsed document as third argument.  
And here you are passing the sentence. To overcome this error, you can do
following :

    
    
    tagged_sentences = [ nltk.pos_tag(token) for token in tokens]
    class doc():
        pass
    IN = re.compile(r'.*\bin\b(?!\b.+ing)')
    doc.headline=["test headline for sentence"]
    for i,sent in enumerate(tagged_sentences):
        doc.text = nltk.ne_chunk(sent)
        for rel in nltk.sem.relextract.extract_rels('ORG', 'LOC', doc, corpus='ieer', pattern=IN):
            print(nltk.sem.rtuple(rel) )// you can change it according
    

Try it out..!!!

