Search code examples
python-3.xnameerror

Why I am getting this "NameError: name 'trainingData' is not defined"


I a trying to import training.txt data as follows.

def readTrainingData(training):
    
    trainingData=[]
    
    with open(training.txt) as f:
        
        for line in f:
            a1, a2 = line.strip().split()
            trainingData.append((a1, a2))
    return trainingData 

After that I am trying to use the traingdata to mesure some score as follows:

for pair in trainingData:
  linkScores[pair[0]+''+pair[1]]= computeProximityScore(pair[0],pair[1],'Jaccard',neighbors)

But it's giving an error


---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-17-2532640f4771> in <module>
----> 1 trainingData

NameError: name 'trainingData' is not defined

Would anybody help me,please?

Thanks


Solution

  • I didn't understand what you have tried to when you passed the variable training to the function. But when you open a file you need to do it like that:

    ```with open("file_name.txt") as f:```
    

    Also, you can't access the variable trainingData outside of the function.

    I updated your code(I hope its what you intended to):

    Main( Or any other place you run the function):

    trainingData = readTrainingData("training.txt")
    # The rest of your code.
    

    Your Function:

    def readTrainingData(training):
        trainingData = []
    
        with open(training) as f:
            for line in f:
                a1, a2 = line.strip().split()
                trainingData.append((a1, a2))
        return trainingData