2014-11-03 1497 views
3

我是一個初學者在pythonPython的IndentationError取消縮進不匹配任何外部縮進級別

我有這樣的錯誤:

Error : 
def on_data(self,data): 
        ^
IdentationError : unindent does not match any outer indentation level 

windows 8.1notepad++我的代碼。我不明白爲什麼我有這個錯誤,我關注了標籤和空間。

我想將數據保存在self.file

這裏是我的代碼:

from tweepy import OAuthHandler 
from tweepy.streaming import StreamListener 
from tweepy import Stream 
import tweepy 
import time 



class StdOutListener(StreamListener): 

    def __init__(self,file): 
     self.file = file 

    def on_data(self, data): 

     print data 
     self.file.write(data) 
     return True 

    def on_error(self, status): 
     print status 


def main() : 
    file = open('work.txt','w') 
    listn = StdOutListener(file) 
    consumer_key="" 
    consumer_secret="" 

    access_token="" 
    access_token_secret="" 

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret) 
    auth.set_access_token(access_token, access_token_secret) 
    #api = tweepy.API(auth) 

    #filename=open('helloworld.txt','r') 
    #f=filename.readlines() 
    #filename.close() 

    #for line in f: 
    # api.update_status(line) 

    stream = Stream(auth, listn) 
    stream.filter(track=['lol']) 
    file.close() 

回答

18

你混合製表符和空格。不要這樣做。具體來說,__init__函數體是縮進的選項卡,而on_data方法不是。

下面是我的文本編輯器中代碼的截圖;我的製表位設置爲8位(這是Python使用),並選擇了文本,這將導致編輯器顯示連續水平線標籤:

highlighted code with tabs shown as lines

你有你的編輯器設置爲擴展選項卡每第四列代替,所以方法出現排隊。

與運行代碼:

python -tt scriptname.py 

,並解決發現的所有錯誤。然後將您的編輯器配置爲僅使用空格進行縮進;一個好的編輯器會在每次使用TAB鍵時插入4個空格。

+0

Martijn,你怎麼知道OP代碼中使用了哪些空格? (我在帖子中看到的都是空格。) – 2014-11-03 18:47:21

+0

@ ron.rothman:你打開編輯器並檢查源代碼中是否有跳轉選項。 – 2014-11-03 18:48:29

+0

啊,我明白了。謝謝! – 2014-11-03 18:50:49

3

在記事本++,如果你得到這個錯誤只是CTRL + A,按TAB鍵一次,它會無處不在代碼中添加選項卡,然後用shift +選項卡刪除剛剛添加的額外選項卡。它會將您的所有「標籤」更改爲4個空格。當然去設置 - >首選項 - >選項卡設置 - >用空格替換。未來的標籤現在將是4個空格。

2

我有相同的問題不少次。特別是當我嘗試從在線編輯器粘貼幾行代碼時,這些空格未正確註冊爲「製表符」或「空格」。

但是修復很簡單。我只需刪除該特定集合中所有代碼行的間距,並使用正確的選項卡再次將其間隔。這解決了我的問題。

相關問題