为什么我的Python代码在将字典列表加载到Tokenizer对象时出现类型错误,提示字典对象不可调用?

我在使用Jupyter Notebook尝试编写一个使用来自Kaggle的讽刺数据集的讽刺检测模型。我已经将数据集下载到我的电脑上,并将其修改为字典列表。每个字典包含三个键:article_link、is_sarcastic和headline。

我的代码如下,出现了以下错误:


TypeError Traceback (most recent call last) in 7 tokenizer.fit_on_texts(sentences)8—-> 9 my_word_index=tokenizer.word_index()1011 print(len(word_index))

TypeError: ‘dict’对象不可调用

import osimport pandasos.getcwd()import jsonos.chdir('C:/Users/IMALSHA/Desktop/AI content writing/Cousera Deep Neural Networks course/NLP lectures')#加载数据 with open('Sarcasm_Headlines_Dataset.json','r') as json_file:     data_set=json.load(json_file)#定义列表sentences=[]labels=[]urls=[]for item in data_set:    sentences.append(item['headline'])    labels.append(item['is_sarcastic'])    urls.append(item['article_link'])import tensorflow as tffrom tensorflow.keras.preprocessing.text import Tokenizerfrom tensorflow.keras.preprocessing.sequence import pad_sequencestokenizer=Tokenizer(oov_token="<oov>")tokenizer.fit_on_texts(sentences)word_index=tokenizer.word_index()print(len(word_index))print(word_index)sequences=tokenizer.texts_to_sequences(sentences)paded=pad_sequences(sequences)print(paded[2])

回答:

问题出在以下代码:

word_index=tokenizer.word_index()

可能您的意图是将tokenizer的word_index存储到word_index变量中。然而,您却像调用方法/函数一样调用了tokenizer.word_index,但它实际上是一个字典。

因此,我认为您需要进行以下修正:

word_index=tokenizer.word_index

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注