【问题标题】:How do I add the result of a print function ito a list [duplicate]如何将打印功能的结果添加到列表中[重复]
【发布时间】:2022-01-09 16:22:43
【问题描述】:

我有以下定义以打印功能结尾的东西:

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()

我已正确打印出三个结果,但我希望将它们列在一个列表中。我尝试以多种不同的方式将它们分配到一个列表中,但我总是收到以下错误消息:AttributeError: 'NoneType' object has no attribute 'append'。 我不明白为什么我的结果有如果 NoneType 有值,我在这里缺少什么?

ps.:如果我像这样删除打印功能:result = sorted(temp, key = lambda val:val[0])[0][1] 我只收到第三个单词,但至少它有字符串作为类型。

【问题讨论】:

    标签: python nltk text-mining


    【解决方案1】:
    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
    

    返回['corpulent', 'indecence', 'validate']

    【讨论】:

    • 非常感谢!我发誓我也试过这个,但不知何故它也对我有用!也许我之前的代码中有错字或其他东西:,)
    【解决方案2】:
    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)
    

    此代码对我有用!并在列表中给出与函数调用相同的字符串,但 None 值除外

    【讨论】:

      猜你喜欢
      • 2020-04-27
      • 2021-03-18
      • 1970-01-01
      • 1970-01-01
      • 2016-09-01
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2020-04-12
      相关资源
      最近更新 更多