2017-02-17 43 views
1

我有一個python腳本包含以下部分 -Python的正確縮進

import csv 
import mechanize 

""" 
some code here 
""" 

with open('data2.csv') as csvfile: 
    readCSV = csv.reader(csvfile, delimiter=',') 
    for row in readCSV: 
     response2 = browser.open(surl+"0"+row[0]) 
     str_response = response2.read() 
     if "bh{background-color:" in str_response : 
      print "Not Found" 
     else : 

      print "Found " + row[0] 
      s_index=str_response.find("fref=search")+13 
      e_index=str_response.find("</a><div class=\"bm bn\">") 
      print str_response[s_index:e_index] 

當我試圖運行這個文件,它顯示在該行有一個錯誤

str_response = response2.read()

str_response = response2.read() ^IndentationError: unexpected indent

我是python的新手,無法弄清楚這段代碼的正確縮進是什麼。任何人都知道我在這裏做錯了什麼?

+3

你可能混和空間和選項卡縮進。 – Carcigenicate

+1

混合製表符和空格? –

+1

也許你在它前面混合了標籤和空格。複製前一行的所有空白,並用str_response替換前面的空白。 – zwer

回答

4

我通過帖子編輯模式複製了您的代碼,正如其他人所說的,您的縮進混合了製表符和空格。在Python 3中,您需要使用其中一種,但不能同時使用這兩種。

這裏是你的原代碼與標籤標示爲[TB]

import csv 
import mechanize 

""" 
some code here 
""" 

with open('data2.csv') as csvfile: 
    readCSV = csv.reader(csvfile, delimiter=',') 
    for row in readCSV: 
     response2 = browser.open(surl+"0"+row[0]) 
[TB][TB]str_response = response2.read() 
[TB][TB]if "bh{background-color:" in str_response : 
[TB][TB][TB]print "Not Found" 
[TB][TB]else : 

[TB][TB][TB]print "Found " + row[0] 
[TB][TB][TB]s_index=str_response.find("fref=search")+13 
[TB][TB][TB]e_index=str_response.find("</a><div class=\"bm bn\">") 
[TB][TB][TB]print str_response[s_index:e_index] 

,這裏是用4個空格代替標籤中的同一代碼:

import csv 
import mechanize 

""" 
some code here 
""" 

with open('data2.csv') as csvfile: 
    readCSV = csv.reader(csvfile, delimiter=',') 
    for row in readCSV: 
     response2 = browser.open(surl+"0"+row[0]) 
     str_response = response2.read() 
     if "bh{background-color:" in str_response : 
      print "Not Found" 
     else : 

      print "Found " + row[0] 
      s_index=str_response.find("fref=search")+13 
      e_index=str_response.find("</a><div class=\"bm bn\">") 
      print str_response[s_index:e_index] 
+0

謝謝!我完全不知道空間和標籤。它正在工作! –