Python的IndentationError

2024-04-26 00:17:45 发布

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

我目前正在尝试为一个使用Python、Elasticsearch和Kibana的项目传输tweet。你知道吗

在运行Python脚本时,我遇到了一个IndentationError,我不明白为什么,有人能帮我解决这个问题吗?你知道吗

提前谢谢。你知道吗

我的Python脚本:

import json
import tweepy
import textblob
import elasticsearch

from tweepy import OAuthHandler, Stream
from tweepy.streaming import StreamListener
from textblob import TextBlob
from elasticsearch import Elasticsearch

consumer_key = '...'
consumer_secret = '...'
access_token = '...'
access_token_secret = '...'

elastic_search = Elasticsearch()

class MyStreamListener(StreamListener):
    def on_data(self, data):
        dict_data = json.loads(data)
        tweet = TextBlob(dict_data["text"])

        print(tweet.sentiment.polarity)

        if tweet.sentiment.polarity < 0:
            sentiment = "negative"
        elif tweet.sentiment.polarity == 0:
            sentiment = "neutral"
        else:
            sentiment = "positive"

        print(sentiment)

        elastic_search.index(index="sentiment",
                 doc_type="test-type",
                 body={"author": dict_data["user"]["screen_name"],
                       "date": dict_data["created_at"],
                       "message": dict_data["text"],
                       "polarity": tweet.sentiment.polarity,
                       "subjectivity": tweet.sentiment.subjectivity,
                       "sentiment": sentiment})

        return True

    def on_failure(self, status):
        print(status)

if __name__ == '__main__':
    listener = MyStreamListener()

    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)

    stream = Stream(auth, listener)
    stream.filter(track=['congress'])

# user_choice = input("Please choose a Hashtag... : ")
# retrieve_tweets = api.search(user_choice)

错误消息:

File "sentiment.py", line 21
    tweet = TextBlob(dict_data["text"])
                                      ^
IndentationError: unindent does not match any outer indentation level

Tags: fromimporttokensearchdatasecretaccessconsumer
1条回答
网友
1楼 · 发布于 2024-04-26 00:17:45

你的确有标签。你知道吗

    def on_data(self, data):
        dict_data = json.loads(data)
# ^ tab and 4 spaces here
        tweet = TextBlob(dict_data["text"])
# ^ 8 spaces here           
        print(tweet.sentiment.polarity)
# ^ ^ two tabs here (equal 16 spaces)

请注意,SO站点中的表示将选项卡转换为空格,但编辑器模式将显示选项卡:

indentation

相关问题 更多 >