-1

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.

  • You already knew how to do this. (Hint: how is `temp` created each time through the loop? Why not use the same technique again to handle the `entries`?) – Karl Knechtel Aug 17 '22 at 01:58

2 Answers2

0
from nltk.corpus import words
import nltk
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']):
    result_2=[]
    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_2.append(sorted(temp, key = lambda val:val[0])[0][1])
        result = print(sorted(temp, key = lambda val:val[0])[0][1])
    return  result, result_2 
a,b=answer_nine()
print(a)

print(b)

this code works for me! and gives the same strings from the function call in a list, except the None value

0
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']

Ming
  • 479
  • 2
  • 11
  • thank you so much! I swear I tried this one as well but somehow it works for me as well! maybe there was a typo in my code previously or something :,) – potato_for_life Dec 03 '21 at 10:27