2017-02-17 45 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

谢谢!我完全不知道空间和标签。它正在工作! –