我的目标是识别python文件中代码行的精确缩进。由于我将在某个位置检测语句,因此确定一行所需的缩进对于实现我的目标很重要。这个问题可以用下面的例子来解释:
First Scenario
#A.py
a=0 <----------- indentation '0' spaces or '0' \t
while a<5: <----------- indentation '0' spaces or '0' \t
print a <----------- indentation '4' spaces or '1' \t
a=a+1 <----------- indentation '4' spaces or '1' \t
Second scenario
#A.py
a=0 <----------- indentation '0' spaces or '0' \t
while a<5: <----------- indentation '0' spaces or '0' \t
print a <----------- indentation '8' spaces or '2' \t
a=a+1 <----------- indentation '8' spaces or '2' \t由于我正在检查一个由许多文件组成的应用程序,因此我遇到了具有上述场景的文件。我想知道如何确定python文件中任何行的缩进?
发布于 2014-03-04 00:50:01
请注意,您选择用来确定缩进的方法可能会对性能产生重大影响。例如,虽然您可以使用正则表达式来执行测量前导空格的任务,但有一些更简单、更有效的方法可以做到这一点。
import re
line = ' Then the result is even.'
r = re.compile(r"^ *")
%timeit len(line) - len(line.lstrip()) # 1000000 loops, best of 3: 0.387 µs per loop
%timeit len(re.findall(r"^ *", line)[0]) # 100000 loops, best of 3: 1.94 µs per loop
%timeit len(r.findall(line)[0]) # 1000000 loops, best of 3: 0.890 µs per loop其他答案中的正则表达式速度较慢的原因是,正则表达式是一个状态机,在构造正则表达式时编译。在内部有一个缓存,但即便如此,最好还是自己手工编译和重用正则表达式。
重要注意事项: Python将制表符解释为8个空格的缩进,因此在求值之前,您还需要使用等量的空格量对文字制表符进行.replace()。
编辑后添加: Python解析器本身并不关心特定的缩进级别,只关心给定的“块”始终缩进。缩进量的增加实际上被忽略并被剥离,取而代之的是缩进和DEDENT标记。(缩进16个空格,仅→一个缩进标记。)真正重要的是逐行缩进的变化。
发布于 2013-07-30 00:01:51
关于
line = ' \t asdf'
len(re.split('\w', line)[0].replace('\t', ' '))
>>> 10请注意,其他建议的解决方案都不会正确计算选项卡。
发布于 2013-07-30 00:03:29
您可以使用Regex:
import re
with open("/path/to/file") as file:
for mark, line in enumerate(file.readlines()):
print mark, len(re.findall("^ *", line)[0])第一个数字是行号,第二个是缩进。
或者,如果您想要特定的行,请执行以下操作:
import re
with open("/path/to/file") as file:
print len(re.findall("^ *", file.readlines()[3])[0])这将返回第4行的缩进(记住,索引将是您想要的行号-1)。
https://stackoverflow.com/questions/17928533
复制相似问题