【问题标题】:Sentence Generation: TypeError: 'NoneType' object is not subscriptable句子生成:TypeError:“NoneType”对象不可下标
【发布时间】:2019-02-10 20:36:20
【问题描述】:

我有一个代码,用于在 sentence_start 之后给定一个单词生成句子

遇到错误的代码:

def generate_sentences(model, n, index_to_word, word_to_index):
    for i in range(n):
        sent = None
        while not sent:
            for i in range(len(arr)):
                sent = generate_sentence(arr[i], model, index_to_word, word_to_index)
                # print (arr[i])
                print_sentence(sent, index_to_word)
        print("\n")

这里是被调用的函数:

def generate_sentence(anot, model, index_to_word, word_to_index, min_length=5):
    # We start the sentence with the start token
    new_sentence = [word_to_index[SENTENCE_START_TOKEN], word_to_index[anot]]
    # Repeat until we get an end token
    while not new_sentence[-1] == word_to_index[SENTENCE_END_TOKEN]:
            next_word_probs = model.predict(new_sentence)[-1]
            samples = np.random.multinomial(1, next_word_probs)
            sampled_word = np.argmax(samples)
            new_sentence.append(sampled_word)
            # Seomtimes we get stuck if the sentence becomes too long, e.g. "........" :(
            # And: We don't want sentences with UNKNOWN_TOKEN's
            if len(new_sentence) > 100 or sampled_word == word_to_index[UNKNOWN_TOKEN]:
                return None
    if len(new_sentence) < min_length:
        return None
    return new_sentence

def print_sentence(s, index_to_word):
    sentence_str = [index_to_word[x] for x in s[1:-1]]
    print(" ".join(sentence_str))
    sys.stdout.flush()

这是回溯:

Traceback (most recent call last):

  File "<ipython-input-10-b9a0a1f5bd04>", line 1, in <module>
    runfile('C:/Users/cerdas/Documents/bil/Code_Latihan/rnn-tutorial-gru-lstm-master/train.py', wdir='C:/Users/cerdas/Documents/bil/Code_Latihan/rnn-tutorial-gru-lstm-master')

  File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
    execfile(filename, namespace)

  File "C:\Users\cerdas\Anaconda3\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/cerdas/Documents/bil/Code_Latihan/rnn-tutorial-gru-lstm-master/train.py", line 53, in <module>
    generate_sentences(model, 20, index_to_word, word_to_index)

  File "C:\Users\cerdas\Documents\bil\Code_Latihan\rnn-tutorial-gru-lstm-master\utils.py", line 190, in generate_sentences
    print_sentence(sent, index_to_word)

  File "C:\Users\cerdas\Documents\bil\Code_Latihan\rnn-tutorial-gru-lstm-master\utils.py", line 179, in print_sentence
    sentence_str = [index_to_word[x] for x in s[1:-1]]

TypeError: 'NoneType' object is not subscriptable

我怀疑是函数print_sentence(sent, index_to_word)引起的错误 我试图编辑缩进以从循环中排除 print_sentence 函数。

但输出只读取数组arr的最后一个元素

【问题讨论】:

  • 如果generate_sentence() 返回None 那么你会得到这个错误,因为你不能迭代None 对象。由于您有一些内置标准可以返回None,我怀疑是这种情况。您可能想尝试在 print_sentence() 中捕获此错误,以查看哪些输入会产生此行为,以便您可以在代码中优雅地处理它们。
  • 你故意return None在某些情况下generate_sentence。但无论该函数返回什么,您都将其分配给sent,然后用sent 调用print_sentence。然后,无论你传递给print_sentence,它都会尝试循环。那就是问题所在;正确的修复取决于您想要做什么。你为什么返回 None,当你这样做时你想发生什么?如果你能解释这一点,应该很容易实现你解释的任何内容。

标签: python nonetype sentence


【解决方案1】:

什么错误信息

TypeError: 'NoneType' object is not subscriptable

意思是,是你的线

sentence_str = [index_to_word[x] for x in s[1:-1]]

正在尝试访问 index_to_word[x]s[1:-1],尽管其中一个似乎是 None

看到您没有提供调用 generate_sentences 的信息,我们只能推测是什么原因造成的。

我建议你添加一个 if 子句,以确保你不会尝试打印一个句子,即None:

print_sentence(sent, index_to_word)

应该替换为

if sent is not None:
    print_sentence(sent, index_to_word)

【讨论】:

  • if sent: 就足够了。 is not None 是多余的。
  • 引用 PEP8:“另外,当您真正的意思是 if x is not None 时,请注意不要写 if x - 例如,在测试默认为 None 的变量或参数是否设置为其他值时。另一个value 可能具有在布尔上下文中可能为 false 的类型(例如容器)!"
猜你喜欢
  • 1970-01-01
  • 2021-12-14
  • 2020-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-05
  • 2021-02-14
  • 2019-08-12
相关资源
最近更新 更多