Search code examples
pythonnltktext-mining

How do I add the result of a print function ito a list


I have the follwing def what ends with a print function:

from nltk.corpus import words
nltk.download('words')
correct_spellings = words.words()
from nltk.metrics.distance import jaccard_distance
from nltk.util import ngrams
from nltk.metrics.distance  import edit_distance    
        
def answer_nine(entries=['cormulent', 'incendenece', 'validrate']):
    for entry in entries:
        temp = [(jaccard_distance(set(ngrams(entry, 2)), set(ngrams(w, 2))),w) for w in correct_spellings if w[0]==entry[0]]
        result = print(sorted(temp, key = lambda val:val[0])[0][1])
    return  result 
answer_nine()

I have the three results correctly printed out, but I would like to have them in a list. I tried to assign them into a list in many different ways but I always receive the following error message: AttributeError: 'NoneType' object has no attribute 'append'. I do not understand why does my result has a NoneType if it has values, what do I missing here?

ps.: if I remove the print function like this: result = sorted(temp, key = lambda val:val[0])[0][1] I receive back only the third word but at least it has string as a type.


Solution

  • def answer_nine(entries=['cormulent', 'incendenece', 'validrate']):
        result = []
        for entry in entries:
            temp = [(jaccard_distance(set(ngrams(entry, 2)), set(ngrams(w, 2))),w) for w in correct_spellings if w[0]==entry[0]]
            result.append(sorted(temp, key = lambda val:val[0])[0][1])
        return result
    

    returns ['corpulent', 'indecence', 'validate']