-1

the objective is to extract from the text the sentences before the word Definition or indications

def extract(doc):

    if( len(doc) != 0 ):
        if ('Definition' in doc):
                sentence = doc.split('Definition')[0]  

        elif ('Definition' not in doc and 'indications' in doc):
                sentence = doc.split('indications')[0]

        return sentence 
    else :
        return doc

It return error : UnboundLocalError: local variable 'sentence' referenced before assignment

Ahmed Bk
  • 1
  • 1
  • and your question is? why you get that error ? – Rabinzel May 31 '22 at 13:21
  • 2
    You have an `if` and an `elif`, so logically there could be an `else case` (but don't): in that case `sentence` hasn't been assigned – doctorlove May 31 '22 at 13:23
  • here is the same issue resolved before. [UnboundLocalError](https://stackoverflow.com/a/10851939/8247037) – ucatbas May 31 '22 at 13:33
  • Does this answer your question? [UnboundLocal Error onfile](https://stackoverflow.com/questions/25569994/unboundlocal-error-onfile) – Joooeey May 31 '22 at 14:07

2 Answers2

0

You can try the below code.This is a simple method.we can just print the output just after the if and and elif statement.And we can also add an else statement to print if there is no word "Dosage" and "Contradictions" in the sentence.

def just_indication(doc):

if( len(doc) != 0 ):
    if ('Dosage' in doc):
            sentence = doc.split('Dosage')[0]  
            print(sentence)
    elif ('Dosage' not in doc and 'Contraindications' in doc):
            sentence = doc.split('Contraindications')[0]
            print(sentence)
     
    else:
         print("Error! word Dosage and Contraindications not present in doc")
    
else:
    print("doc empty")
           
just_indication("this is the sentence which has the word Contraindications in it")
-1

I think it's because you declare "sentence" in an if statment, try declar it right after your def, like this :

def just_indication(doc):
    sentence = ""
    if( len(doc) != 0 ):
        if ('Dosage' in doc):
                sentence = doc.split('Dosage')[0]  

        elif ('Dosage' not in doc and 'Contraindications' in doc):
                sentence = doc.split('Contraindications')[0]

        return sentence 
    else :
        return doc