一、需求描述

1、我有一个txt文档,里面的数据如下:

NG 20211228085937212 Unknow  29
OK 20211228085937245 EAN_13 2112345678917 44
OK 20211228085937313 EAN_13 2112345678917 58
OK 20211228085937428 EAN_13 2112345678917 38
NG 20211228085937484 Unknow  59
OK 20211228085937511 EAN_13 2112345678917 46
NG 20211228085937597 Unknow  36
NG 20211228085937642 Unknow  33
OK 20211228085937676 EAN_13 2112345678917 47
OK 20211228085937739 EAN_13 2112345678917 43
OK 20211228085937806 EAN_13 2112345678917 40
OK 20211228085937840 EAN_13 2712345672917 56
NG 20211228085937906 Unknow  30
OK 20211228085937972 EAN_13 2112345678917 73
NG 20211228085938084 Unknow  26
NG 20211228085938107 Unknow  30

2、我要做的事情如下:

(1)读取每一行末尾的数字(这些数字长度不定)

(2)读的数字不包含具有NG字符的句子

(3)输出一个列表,里面全是符合上述规则的数字

二、实战演练

1、代码如下:

from typing import List

class TxtHandler(object):

    def __init__(self, filepath):
        self.filepath = filepath

    def writer(self, content):
        with open(self.filepath, "w+") as f:
            f.write(content)

    def reader(self):
        with open(self.filepath, "r") as f:
            return f.read()


class GetTime(object):

    def txt(self, way: str) -> str:
        # 通过文件对象,获取文件内容
        return TxtHandler(way).reader()

    def enter_cut(self, txt: str) -> List[str]:
        # 遇到回车就截取
        # 输入内容是一个段落,需要读取每行数据,如果开头不是NG,就放到列表里面
        return [line for line in  txt.splitlines() if "NG" != line[0:2]]

    def space_cut_and_get_time(self, sentence_list: List[str]) -> List[int]:
        # 遇到空格就截取,并取最后的数据(期望的数字)
        return [int(sentence.split(" ")[-1]) for sentence in sentence_list]

if __name__ == "__main__":
    way = r"C:\Users\yeqinfang\Desktop\临时文件\数据记录\13.txt"
    gt = GetTime()
    content = gt.txt(way)
    lines_list = gt.enter_cut(content)
    time_list = gt.space_cut_and_get_time(lines_list)
    print(time_list)
    print(max(time_list))
    print(min(time_list))

2、效果如下:

 

更多推荐

python读取文件段落,并截取每行指定字符