【问题标题】:Getting a type error when trying to run a basic for loop (Python)尝试运行基本 for 循环时出现类型错误(Python)
【发布时间】:2021-09-22 09:23:11
【问题描述】:

我有一个我认为可能是基本问题的问题,我是 Python 新手,但我已经四处搜索,但没有发现任何足够相似的问题。当我运行以下 Python 代码时,出现以下错误:

TypeError: string indices must be integers

我不确定为什么会出现这种类型错误,sentence.labels[0].score 代码应该返回一个浮点数,但其余的应该返回一个字符串,Python 告诉我错误位于“for i in tweets['text'].to_list():”行。

sentiment = []
confidence = []

for i in tweets['text'].to_list():
    sentence = flair.data.Sentence(tweets)
    sentiment_model.predict(sentence)
    
    sentiment.append(sentence.labels[0].value)
    confidence.append(sentence.labels[0].score)
    
tweets['sentiment'] = sentiment
tweets['confidence'] = confidence

非常感谢任何帮助

感谢您的宝贵时间

【问题讨论】:

  • 所以,看起来tweets 已经是一个列表:for i in tweets: 应该怎么做?
  • 要正确回答,我们需要知道什么是“推文”。如果输出不是太大,请执行 print("tweets") 并向我们展示输出。

标签: python python-3.x list loops


【解决方案1】:

如果 tweets 是一个列表,那么你必须在 tweets[int] 中放入一个整数类型,它是列表中元素的索引。

'text' 是字符串类型,str 类型不能用作索引,如果你想做一些 "text" 存在于 >tweets 您可以尝试将其更改为 tweets[tweets.index("text")]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-09
    • 1970-01-01
    • 2014-03-27
    • 2021-12-12
    • 1970-01-01
    相关资源
    最近更新 更多