Created
July 7, 2015 16:41
-
-
Save peterbe/03044a346a3298f259ba to your computer and use it in GitHub Desktop.
Find what indentation a file uses
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import re | |
from collections import defaultdict | |
start = re.compile('^\s+') | |
def avg(fn): | |
prev = None | |
diffs = [] | |
for line in open(fn): | |
if not line.strip(): | |
continue | |
try: | |
L = len(start.findall(line)[0]) | |
except IndexError: | |
L = 0 | |
if prev is not None: | |
diffs.append(abs(prev - L)) | |
prev = L | |
counts = defaultdict(int) | |
for diff in diffs: | |
if diff == 0: | |
continue | |
counts[diff] += 1 | |
counts = sorted(counts.items(), lambda x,y: cmp(y[1], x[1])) | |
try: | |
most_common = counts[0] | |
return most_common[0] | |
except IndexError: | |
return None | |
if __name__ == '__main__': | |
import sys | |
filenames = sys.argv[1:] | |
for filename in filenames: | |
a = avg(filename) | |
if a: | |
print a, '\t', filename |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage:
And the output can look like this: