检查下一行是否有比当前lin更多的前导空格

2024-10-01 02:18:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样结构的文本文件,我需要通读每一行。你知道吗

XXXX
....
YYYY
    ZZZZ
    ZZZZ
    ....
YYYY
    ZZZZ
    ZZZZ
    ....

....表示上述对象的任意个数。你知道吗

文件被读入名为textList的列表中

lines = enumerate(textList)
for i, line in lines:
    #read in the XXXXs
    if line == "YYYY"
        # from this location, get the next line in lines
        # i.e. (i, lines = lines.__next__())
        # until the next line has the same or lower amount
        # of whitespace than the amount of whitespace before
        # the line that has "YYYY"

我试过几种不同的方法,但我不断得到无限的循环。我知道这是可能的,但我就是没能弄明白

当前脚本:(给定索引错误)

def getIndentLevel(line):
    tabCount = len(line) - len(line.lstrip(' '))
    #print(tabCount)
    return tabCount

textList = ["XXXX", 
            "XXXX", 
            "XXXX",
            "YYYY",
            "    ZZZZ",
            "    ZZZZ",
            "YYYY",
            "    ZZZZ",
            "    ZZZZ"]
lines = enumerate(textList)

for i, line in lines:
    if line.lstrip(' ') == "YYYY":
        print("YYYY found")
        cur = getIndentLevel(textList[i])
        while True:
            nxt = getIndentLevel(textList[i+1])
            if nxt <= cur:
                break
            i, line = lines.__next__()
            print(i, line)
            #nxt = getIndentLevel(textList[i+1])

Tags: theiniflinenextnxtlinesprint
2条回答

此脚本解决了以下问题:

def getIndentLevel(line):
    tabCount = len(line) - len(line.lstrip(' '))
    return tabCount

textList = ["XXXX", 
            "XXXX", 
            "XXXX",
            "YYYY",
            "    ZZZZ",
            "    ZZZZ",
            "YYYY",
            "    ZZZZ",
            "    ZZZZ",
            "",
            "",
            "",
            "XXXX",
            "XXXX",]
lines = enumerate(textList)

for i, line in lines:
    if line.lstrip(' ') == "YYYY":
        print("YYYY found")
        cur = getIndentLevel(textList[i])
        nxt = getIndentLevel(textList[i+1])
        while True:
            if nxt <= cur:
                break
            i, line = lines.__next__()
            print(i, line)
            try:
                nxt = getIndentLevel(textList[i+1])
            except:
                break

我不认为你需要列举。你知道吗

for  i in range(len(textList)) :   
  numWhiteSpace = len(textList[i]) - len(textList[i].lstrip())
  if i == 0:
    continue
  else:
    if numWhiteSpace > (len(textList[i-1]) - len(textList[i-1].lstrip())):
      print(textList[i])

相关问题 更多 >