invert reindent.py(标签空格)

时间:2011-05-17 14:01:43

标签: python indentation

afaik reindent.py(在标准的python示例中可用)有一个tokenizer,允许它根据缩进级别而不是每个级别的空间数量(在不良代码中可能会有所不同)进行智能重新定义< / p>

不幸的是它强制执行4空格缩进,但我想要标签,因为1个标签== 1缩进级别比x空格更合乎逻辑。

this问题没有合适的答案:

  • 我不关心pep-8(我知道如何编写我的代码)
  • 已安装vim,但:retab!无法处理不一致的缩进
  • 所有工具也将用于对齐的空格(!=缩进)转换为制表符。

一种方法是使用reindent.py然后做某事。像:

#!/usr/bin/env python3
from re import compile
from sys import argv

spaces = compile("^ +")
multistr = False
for line in open(argv[1]):
    num = 0
    if not multistr:
        try:
            num = len(spaces.search(line).group(0)) // 4
        except AttributeError:
            pass
    print("\t"*num + line[num*4:-1])
    if line.count('"""') % 2 == 1:
        multistr = not multistr

但这很苛刻。是不是没有非狂热版的reindent.py?

PS:为什么强调// 4是评论而不是截断分部?


以下脚本应该可以解决这个问题,但是我错过了,或者tokenize是错误的(或python文档中的示例)

#!/usr/bin/env python3

from tokenize import *
from sys import argv

f = open(argv[1])
def readline():
    return bytes(f.readline(), "utf-8")

tokens = []
ilvl=0
for token in tokenize(readline):
    if token.type == INDENT:
        ilvl+=1
        tokens.append((INDENT, "\t"*ilvl))
    else:
        if token.type == DEDENT:
            ilvl-=1
        tokens.append(token)

print(untokenize(tokens).decode('utf-8'))

1 个答案:

答案 0 :(得分:3)

在unix中使用sed,你可以用一行来获取它:

sed -r ':f; s|^(\t*)\s{4}|\1\t|g; t f' file

编辑:这只适用于行首的空格。