lundi 1 mars 2021

Local variable index referenced before an assignment

I have been trying to fetch skills from a resume. Below code works fine for me to extract skills:

def getSkills(sentences):
    try:
        sen=[]
        z=0
        for words in sentences:
            for i in range(len(words)):
                if(words[i][0].lower()=='skills') and words[i][1]=='NNP':
                    index =[z,i]
                    break
            z+=1

        skills=[]
        for i in sentences[index[0]][index[1]+1:]:
            if i[0].isalpha() and i[1]=='NNP':
                skills.append(i[0])

        return skills
    except:
        return None

Output:

'Skills': ['Java', 'Python', 'R', 'SQL', 'Apache', 'Spark', 'JavaScript']

But when I put elif to check if the skill is empty and to open up a rawtext.json then it gives me an error of UnboundLocalError: local variable 'index' referenced before assignment. I have searched and tried making it global but still no luck. Below is the snippet with elif logic:

def getSkills(sentences):
    sen=[]
    z=0
    for words in sentences:
        for i in range(len(words)):
            if(words[i][0].lower()=='skills') and words[i][1]=='NNP':
                index =[z,i]
                break
        z+=1

    skills=[]
    for i in sentences[index[0]][index[1]+1:]:
        if i[0].isalpha() and i[1]=='NNP':
            skills.append(i[0])
            return skills
        elif skills == []:
            with open('rawtext.json','r', encoding='utf-8') as f:
                data = json.load(f)
            result = [x["name"].replace("@", " ").lower() for x in data]
            print(result)
        else:
            return None

Result:

for i in sentences[index[0]][index[1]+1:]:
   UnboundLocalError: local variable 'index' referenced before assignment

What should I do in this case?

Aucun commentaire:

Enregistrer un commentaire