如何找出文本文件中每行开头的制表符数量?

问题描述 投票:0回答:1

我有一个文本文件,其中每行可能以多个选项卡开头,包括没有选项卡。 例如,第一行没有制表符,第二行有 1 个制表符,第三行有 2 个制表符:

Chapter 1 
    1
        1.1
Chapter 2
    1
        1.1

是否可以使用Python获取每行开头的制表符数量?谢谢。

python python-3.x text-processing
1个回答
0
投票

使用

re.findall
map
len

import re

list(map(len, re.findall('^\s*', text, flags=re.M)))

输出:

[0, 1, 2, 0, 1, 2]

使用的输入:

text = '''Chapter 1 
\t1
\t\t1.1
Chapter 2
\t1
\t\t1.1'''
© www.soinside.com 2019 - 2024. All rights reserved.