Skip to main content
 首页 » 编程设计

Python之检查文件中行的顺序

2025年05月04日17dudu

如何检查文件中行​​的顺序?

示例文件:

a b c d e f 
b c d e f g 
1 2 3 4 5 0 

要求:

  1. 所有以 a 开头的行必须在以 b 开头的行之前。
  2. 以a开头的行数没有限制。
  3. 以 a 开头的行可能存在也可能不存在。
  4. 包含整数的行,必须跟在以 b 开头的行之后。
  5. 数字行必须至少有两个整数后跟零。
  6. 不满足条件必须引发错误。

我最初想的是一个相当冗长的 for 循环,但是失败了,因为我无法索引 line[0] 之外的行。另外,我不知道如何定义一条线相对于其他线的位置。这些文件的长度没有限制,因此内存也可能是一个问题。

非常欢迎任何建议!对于这个困惑的新手来说,简单易读是受欢迎的!

谢谢, 海鲜。

请您参考如下方法:

一种直接的迭代方法。这定义了一个函数来确定从 1 到 3 的线型。然后我们遍历文件中的线。未知的线型或小于任何先前线型的线型将引发异常。

def linetype(line): 
    if line.startswith("a"): 
        return 1 
    if line.startswith("b"): 
        return 2 
    try: 
        parts = [int(x) for x in line.split()] 
        if len(parts) >=3 and parts[-1] == 0: 
            return 3 
    except: 
        pass 
    raise Exception("Unknown Line Type") 
 
maxtype = 0 
 
for line in open("filename","r"):  #iterate over each line in the file 
    line = line.strip() # strip any whitespace 
    if line == "":      # if we're left with a blank line 
        continue        # continue to the next iteration 
 
    lt = linetype(line) # get the line type of the line 
                        # or raise an exception if unknown type 
    if lt >= maxtype:   # as long as our type is increasing 
        maxtype = lt    # note the current type 
    else:               # otherwise line type decreased 
        raise Exception("Out of Order")  # so raise exception 
 
print "Validates"  # if we made it here, we validated