语句生成:TypeError:“NoneType”对象不是subscriptab

2024-09-26 22:55:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个代码来生成一个接一个单词的句子

遇到错误的代码:

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

以下是被调用的函数:

^{pr2}$

这是回溯:

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的最后一个元素


Tags: toinpyindexlinecodeuserssentence
1条回答
网友
1楼 · 发布于 2024-09-26 22:55:09

什么错误消息

TypeError: 'NoneType' object is not subscriptable

意思是,这是你的台词吗

^{pr2}$

正在尝试访问index_to_word[x]和{},尽管其中一个似乎是{}

鉴于您没有提供generate_sentences被调用的信息,我们只能推测是什么导致了这种情况。在

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

print_sentence(sent, index_to_word)

应替换为

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

相关问题 更多 >

    热门问题