使用python根据文本文件中的特定模式提取行数据

如何解决使用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)

解决方法

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

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.basenamepathlib.Path.name

,

我遇到了一个非常相似的问题,并通过用regex搜索特定行“ key”(在您的情况下为MLT-TRR”),然后指定要从该行获取哪些“字节”来解决该问题。然后附加所选数据到一个数组。

#include <iostream>
#include <vector>
#include <string>

enum class E { TYPE_0,TYPE_1 };

template<typename T1,typename T2>
struct AandB
{
   T1 v0;
   T2 v1;
   E type;
   AandB() : type{ E::TYPE_0 } {}
   AandB& operator= (const AandB& rhs) // one operator =
   {
      v0 = rhs.v0;
      v1 = rhs.v1;
      type = rhs.type;
      return *this;
   }

   std::string strType() const { return std::to_string(static_cast<int>(type)); }
};

int main()
{
   using C0 = std::vector<float>;
   using C1 = std::vector<int>;
   AandB<C0,C1> obj;
   std::cout << obj.strType() ; // Prints: 0
}

如果将正则表达式设置为查找“ MLT_TRR ?????文件夹:'Picture。'”,则它将跳过没有更多信息的任何行。

对于问题的第二部分。 我怀疑您的文件名是否为固定长度,因此上述方法无法工作,因为您无法指定要提取的字节数。此代码从文件路径中提取名称和扩展名,您可以将其应用于提取的任何内容从每一行开始。

import re #Import the regex function
#Make empty arrays:
    P190=[] #my file
    shot=[] #events in my file (multiple lines of text for each event)
    S011east=[] #what I want
    S011north #another thing I want

#Create your regex:
    S011=re.compile(r"^S0\w*\W*11\b") 

#search and append:
    #Open P190 file
    with open(import_file_path,'rt') as infile:
        for lines in infile:
            P190.append(lines.rstrip('\n'))       
    #Locate specific lines and extract data
    for line in P190:
        if  S011.search(line)!= None:
            easting=line[47:55]
            easting=float(easting)
            S011east.append(easting)
            northing=line[55:64]
            northing=float(northing)
            S011north.append(northing)
        

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-