首页 > 解决方案 > 使用python根据文本文件中的特定模式提取行数据

问题描述

我有一个巨大的报告文件,其中包含一些数据,我必须对以代码“MLT-TRR”开头的行进行一些数据处理现在我已经提取了脚本中以该代码开头的所有行并将它们放在单独的文件。新文件如下所示 - Rules.txt。

MLT-TRR                         Warning     C:\Users\Di\Pictures\SavedPictures\top.png  63   10   Port is not registered [Folder: 'Picture']

MLT-TRR                         Warning     C:\Users\Di\Pictures\SavedPictures\tree.png 315  10   Port is not registered [Folder: 'Picture.first_inst']

MLT-TRR                         Warning     C:\Users\Di\Pictures\SavedPictures\top.png  315  10   Port is not registered [Folder: 'Picture.second_inst']

MLT-TRR                         Warning     C:\Users\Di\Pictures\SavedPictures\tree.png 317  10   Port is not registered [Folder: 'Picture.third_inst']

MLT-TRR                         Warning     C:\Users\Di\Pictures\SavedPictures\top.png  317  10   Port is not registered [Folder: 'Picture.fourth_inst']

对于这些行中的每一行,我必须提取位于“[文件夹:'图片”之后的数据如果在“[文件夹:'图片”之后没有数据,就像我的第一行一样,那么跳过该行并继续到下一行。我还想提取每一行的文件名-top.txt、tree.txt

我想不出更简单的方法来做到这一点,因为这涉及到一个循环并且变得更加混乱。我有什么办法可以做到这一点吗?仅提取文件路径和每行的结尾数据。

import os
import sys
from os import path
import numpy as np


folder_path = os.path.dirname(os.path.abspath(__file__))
inFile1 = 'Rules.txt'
inFile2 = 'TopRules.txt'

def open_file(filename):
    try:
        with open(filename,'r') as f:
            targets = [line for line in f if "MLT-TRR" in line]
            print targets
        f.close()
        with open(inFile1, "w") as f2:
            for line in targets:
                f2.write(line + "\n")
        f2.close()
        
    except Exception,e:
        print str(e)
    exit(1)


if __name__ == '__main__':
    name = sys.argv[1]
    filename = sys.argv[1]
    open_file(filename)

标签: pythonfiletextpattern-matching

解决方案


要提取文件名和其他数据,您应该能够使用正则表达式:

import re

for line in f:
    match = re.match(r"^MLT-TRR.*([A-Za-z]:\\[-A-Za-z0-9_:\\.]+).*\[Folder: 'Picture\.(\w+)']", line)
    if match:
        filename = match.group(1)
        data = match.group(2)

这假设后面的数据'Picture.只包含字母数字字符和下划线。[A-Za-z0-9_:\\.]如果您有奇怪的文件名,您可能必须更改文件名部分中允许的字符。它还假定文件名以 Windows 驱动器号(即绝对路径)开头,以便更容易与行中的其他数据区分开来。

如果您只想要文件名的基本名称,那么在提取它之后您可以使用os.path.basenameor pathlib.Path.name


推荐阅读