Python - 检查文件中行​​的顺序

标签 python file lines

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

示例文件:

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

关于Python - 检查文件中行​​的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1931802/

相关文章:

java - 如何获取线与缓冲图像或矩形碰撞的点?

python - django/python - 在我的基础设施和客户之间交换数据的推荐安全方法是什么?

python - 用 2d 矩阵填充 4D 矩阵

java - Android 获取文件夹中的每个文件

python - 从文件读取并根据文件输入实例化新类

python - 读取多元素列表,查找元素并在 python 中打印出来

python - 跨时间暗淡的每个网格单元的线性回归

Python 字典故障安全

javascript - 如何使用 Javascript 处理上传的文件

python : split text to list of lines